Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.