Last active
May 10, 2021 04:20
-
-
Save zlatko-minev/89d7534b4163299ebd98bb17610f5b89 to your computer and use it in GitHub Desktop.
Break out tables from a tex or latex file into separate tables .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
#!python | |
""" | |
Break out tables from a tex or latex file into separate tables .tex files.. | |
To see help | |
>> python latex_replace_text_by_input_file.py -h | |
To run user either of: | |
>> python latex_replace_text_by_input_file.py -f epr-main | |
>> python latex_replace_text_by_input_file.py -f epr-main -d _SUBMIT_ | |
@license: APACHE 2.0 | |
@author: Zlatko K. Minev (2021) | |
""" | |
import argparse | |
import re | |
from pathlib import Path | |
def latex_replace_text_by_input_file(text:str, FOLDER:str, | |
start = r'\begin{tabular}', | |
end = r'\end{tabular}' , | |
prefix = r'table') -> str: | |
"""Replaces text, such as tables of the file by input files | |
and saves the input files. | |
""" | |
# without r, Use the syntax "\\" within the string literal to represent a single backslash. | |
start2= start.replace('\\', r"\\") | |
end2 = end.replace( '\\', r"\\") | |
pattern = f"{start2}(.*?){end2}" | |
substrings = re.findall(pattern, text, re.DOTALL) # -> List[Str] | |
print(f'Found {len(substrings)} substrings') | |
text2 = text | |
for n, substring in enumerate(substrings): | |
full_substring = f"{start}{substring}{end}" | |
fn = f"{prefix}{n}.tex" | |
(Path(FOLDER) / fn).write_text(full_substring) | |
text2 = text2.replace(full_substring, "\input{"+fn+"}") | |
return text2 | |
my_args = None | |
# Can use the following to test | |
# my_args= ["-h"] | |
# my_args= ["-f", "epr-main"] | |
# my_args= ["-f", "epr-main", "-d", "_SUBMIT_"] | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description = """ | |
Zlatko's code to break out tables from a tex or latex file into separate tables .tex files.. | |
""") | |
parser.add_argument("--file", "-f", type=str, required=True, help="filename to process, without extension .tex") | |
parser.add_argument("--dir", "-d", type=str, required=False, help="folder for file", default='') | |
args = parser.parse_args(my_args) | |
print(args) | |
### INPUTS ################################ | |
FOLDER=args.dir | |
filename=f'{args.file}.tex'# if FOLDER else f'{args.file}.tex' | |
### CODE ################################## | |
path = Path(FOLDER) / filename | |
print("") | |
print('path.resolve() = ', path.resolve()) | |
print('path.is_file() = ', path.is_file()) | |
text = path.read_text() | |
text2 = latex_replace_text_by_input_file(text, FOLDER) | |
path.write_text(text2) | |
print("") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment