Last active
August 20, 2018 23:04
-
-
Save he7d3r/7ea089af2ecc9138311d15e34aa41241 to your computer and use it in GitHub Desktop.
Fix typos in .tex files
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
#!/usr/bin/python3 | |
# Copyright © 2018 He7d3r <http://he7d3r.mit-license.org> | |
import argparse | |
import re | |
import fileinput | |
from pathlib import Path | |
re_rule = re.compile("<(?:Typo)?\s+(?:word=\"(.*?)\"\s+)?find=\"(.*?)\"\s+replace=\"(.*?)\"\s*\/?>") | |
def fix_typos(typos, filename): | |
print("Processing {} ...".format(filename)) | |
texfile = fileinput.FileInput(filename, inplace=True) | |
for line in texfile: | |
for typo in typos: | |
try: | |
line = re.sub(typo['find'], typo['replace'], line) | |
except Exception as e: | |
#print(typo['find'].pattern, typo['replace'], line) | |
pass | |
print(line.rstrip()) | |
fileinput.close() | |
def process(line): | |
match = re_rule.match(line) | |
if match: | |
find = match.group(2) | |
try: | |
find = re.compile(find) | |
word = match.group(1) | |
replace = re.sub( r'\$(\d)', r'\\\1', match.group(3)) | |
rule = {'find': re.compile(find), 'replace': replace} | |
return rule | |
except Exception as e: | |
raise | |
def get_typos(file): | |
typos = [] | |
with open(file) as f: | |
for line in f: | |
typo = process(line) | |
if typo: | |
typos.append(typo) | |
return typos | |
def tex_files(initial_path): | |
for path in Path(initial_path).glob('**/*.tex'): | |
yield str(path) | |
def main(): | |
parser = argparse.ArgumentParser(description='Fix typos in *.tex using AWB list') | |
parser.add_argument('--typos', help='File which contains the AWB typos') | |
parser.add_argument('--path', help='Path to check recursivelly the .tex') | |
args = parser.parse_args() | |
typos = get_typos(args.typos) | |
for file in tex_files(args.path): | |
fix_typos(typos, file) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment