Skip to content

Instantly share code, notes, and snippets.

@KelSolaar
Created January 24, 2019 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KelSolaar/f8e070102c4f5b832e7c5b7859a21878 to your computer and use it in GitHub Desktop.
Save KelSolaar/f8e070102c4f5b832e7c5b7859a21878 to your computer and use it in GitHub Desktop.
LaTeX - Add Labels
import codecs
import fnmatch
import os
import re
def _sanitize_filename(filename):
"""
Sanitizes given filename.
Parameters
----------
filename : unicode
Filename to sanitize.
Returns
-------
unicode
Sanitized filename.
"""
return re.sub('\s+', ' ', re.sub("[\s,\\(\\)-\\.'/]+", ' ',
filename)).strip()
tex_files = []
for root, dirnames, filenames in os.walk('.'):
for filename in fnmatch.filter(filenames, '*.tex'):
tex_files.append(os.path.join(root, filename))
patterns = {
'\\\\chapter': 'ch',
'\\\\section': 'sec',
'\\\\subsection': 'subsec',
'\\\\subsubsection': 'subsubsec',
'\\\\paragraph' : 'par'
}
for tex_file in tex_files:
with codecs.open(tex_file, encoding='utf8') as tex_f:
lines = tex_f.readlines()
content = []
for i, line in enumerate(lines):
content.append(line)
for pattern, replacement in patterns.items():
match = re.match('%s(\*)?\{(.*)\}' % pattern, line.strip())
if match:
label = _sanitize_filename(match.groups(1)[-1]).replace(' ', '-').lower()
content.append('\\label{%s:%s}\n' % (replacement, label))
with codecs.open(tex_file, 'w', encoding='utf8') as tex_f:
tex_f.write(''.join(content))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment