Created
August 2, 2021 04:55
-
-
Save YakBarber/6468bb621a09c416d853b0c0772315fe to your computer and use it in GitHub Desktop.
Simple script to format the data in a CSV file (exported from Excel, perhaps) into a copy-pastable LaTeX table. It makes it easy to change the format choices if you want something specific.
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
### quick 'n' dirty CSV -> LaTeX table output | |
import csv | |
############################### | |
## stuff you should change ## | |
############################### | |
# the CSV to be table-ized | |
IN_FILENAME = "data.csv" | |
# the output file (will be OVERWRITTEN) | |
OUT_FILENAME = "table.txt" | |
# if you want the table to print to the terminal also | |
DUMP_TO_STDOUT = True | |
# To table-ize the whole CSV file, set to None | |
# If you don't want the whole CSV, give indices of columns you want in a list | |
INCLUDE_COLS = None | |
#INCLUDE_COLS = [0, 1, 2, 10, -1] | |
####################################################### | |
## stuff you might want to change but probably not ## | |
####################################################### | |
LINE_PREFIX = "" # stuff at the start of each line | |
LINE_SUFFIX = r" \\" # stuff at the end of each line | |
CELL_INTER = " & " # stuff between each column | |
LINE_INTER = None # stuff between each line (like \hline)(set None to disable) | |
############################################################ | |
## stuff that does stuff and doesn't need to be touched ## | |
############################################################ | |
def trim_cols(line): | |
if INCLUDE_COLS is not None: | |
out = [] | |
for col in INCLUDE_COLS: | |
out.append(line[col]) | |
return out | |
else: | |
return line | |
with open(IN_FILENAME,"r") as f: | |
out_lines = [] | |
for line in csv.reader(f): | |
line = trim_cols(line) | |
out = LINE_PREFIX if LINE_PREFIX is not None else "" | |
out += CELL_INTER.join(line) | |
out += LINE_SUFFIX if LINE_SUFFIX is not None else "" | |
out_lines.append(out) | |
if LINE_INTER is not None: | |
out_lines.append(LINE_INTER) | |
out_text = "\n".join(out_lines) | |
if DUMP_TO_STDOUT: | |
print(out_text) | |
if OUT_FILENAME is not None: | |
open(OUT_FILENAME,"w").write(out_text) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment