Last active
October 26, 2020 14:34
-
-
Save MrHedmad/f99aaea3da91fa37717eb47d372b9178 to your computer and use it in GitHub Desktop.
Latexify CSV table in Python
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
"""Generated latex code from a CSV file. Can also escape special characters | |
that latex cannot support in a string by themselves, such as _.""" | |
from pathlib import Path | |
def main(csv_path, chars_to_escape=["_"]): | |
csv_path = Path(csv_path) | |
latex = "\\begin{table}\n\t\\centering\n\t\\begin{tabular}{|" | |
with csv_path.open() as csv: | |
header = next(csv).split(",") | |
for i in range(0, len(header)): | |
latex += "c|" | |
latex += "}\n\t\t\\hline\n\t\t" | |
for word in header: | |
word = word.replace("\n", "") | |
word = escape_chars(word, chars_to_escape) | |
latex += f"\\textbf{{{word}}} & " | |
latex = latex[:-2] + "\\\\\n\t\t\\hline\\hline\n\t\t" | |
for line in csv: | |
for word in line.split(","): | |
word = word.replace("\n", "") | |
word = escape_chars(word, chars_to_escape) | |
latex += f"{word} & " | |
latex = latex[:-2] + "\\\\\n\t\t\\hline\n\t\t" | |
latex += "\t\\end{tabular}\n\t\\label{tab:}\n\t\\caption{}\n\\end{table}" | |
out_path = csv_path.parent / (csv_path.stem + "_latexed.txt") | |
with out_path.open("w+") as out: | |
out.writelines(latex.replace('"', "")) | |
return True | |
def escape_chars(string, characters): | |
if type(characters) is str: | |
characters = list(characters) | |
for character in characters: | |
string = string.replace(str(character), ("\\" + character)) | |
return string | |
if __name__ == "__main__": | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument("csv_path", help="Path to the csv file.", type=str) | |
parser.add_argument("--escape", help="Chars to escape", nargs="*", default=["_"]) | |
args = parser.parse_args() | |
main( | |
args.csv_path, args.escape, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment