Created
January 24, 2019 08:52
-
-
Save KelSolaar/f8e070102c4f5b832e7c5b7859a21878 to your computer and use it in GitHub Desktop.
LaTeX - Add Labels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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