Last active
June 22, 2023 23:48
-
-
Save diramazioni/5ac8f2aecb21fcc148bf625c6ec808c3 to your computer and use it in GitHub Desktop.
Convert a CSV table into LaTeX
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
def csv2latex(file_path, sep): | |
with open(file_path, 'r') as file: | |
lines = file.readlines() | |
# count how many column there is | |
col = lines[0].count(sep) + 1 | |
empty_line = sep*int(col-1) | |
start = ['\\begin{table} \n','\caption{Table captions should be placed above the tables.}\label{tab1} \n'] | |
new = start | |
tabular = '\\begin{tabular}{'+'|l|'*col+'}\hline \n' | |
new.append(tabular) | |
for i, line in enumerate(lines): | |
#print(i, line) | |
if empty_line in line: | |
line = line.replace(empty_line,"\hline") | |
else: | |
line = line.replace("_","\_") | |
line = line.rstrip('\n') + '\\\\\n' | |
new.append(line) | |
if i == 0: | |
new.append('\hline \n') | |
end = '''\\hline | |
\\end{tabular} | |
\\end{table} | |
''' | |
new += [l + "\n" for l in end.split("\n")] | |
with open(file_path, 'w') as file: | |
file.writelines(new) | |
### use your csv and separator ie '&' | |
file_path = 'validation.csv' | |
csv2latex(file_path, '&') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment