Created
November 5, 2014 14:21
-
-
Save retrage/aa5ea35282502e0bee3f to your computer and use it in GitHub Desktop.
An excel-style table to tex-style table script
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/python | |
import re | |
import sys | |
def parseCSV(text,delim=','): | |
tokenizer = re.compile(delim+r'|\r?\n|[^'+delim+r'"\r\n][^'+delim+ \ | |
r'\r\n]*|"(?:[^"]|"")*"') | |
tmp = tokenizer.findall(text) | |
data = [] | |
i = 0 | |
j = 0 | |
while i < len(tmp): | |
if tmp[i] == '\t': | |
del tmp[i] | |
elif tmp[i] == '\n': | |
data.append(tmp[j:i]) | |
j = i + 1 | |
i += 1 | |
return data | |
def csv2TeX(text): | |
text = text.replace(r'\\', r'\\textbackslash') | |
text = text.replace(r'\#', r'\\#') | |
text = text.replace(r'\$', r'\\$') | |
text = text.replace(r'\%', r'\\%') | |
text = text.replace(r'\&', r'\\&') | |
text = text.replace(r'\_', r'\\_') | |
text = text.replace(r'\{', r'\\{') | |
text = text.replace(r'\}', r'\\}') | |
text = text.replace(r'\~', r'\\~{}') | |
text = text.replace(r'\^', r'\\^{}') | |
text = text.replace(r'\|', r'\\textbar') | |
csv = parseCSV(text, delim='\t') | |
maxcols = 0 | |
outstr = "" | |
hline = " \\hline" | |
for row in csv: | |
if len(row) > maxcols: | |
maxcols = len(row) | |
for i, cell in enumerate(row): | |
outstr += cell | |
if i < (len(row)-1): | |
outstr += ' & ' | |
outstr += "\\\\" + hline + "\n" | |
outstr = "\\begin{tabular}{|"+"c|"*maxcols+"}" + hline + "\n" + outstr + \ | |
"\\end{tabular}" + "\n" | |
outstr = "\\caption{__CAPTION__}\n" + outstr | |
outstr = outstr+"\\label{__LABEL__}\n" | |
outstr = "\\begin{center}\n" + outstr + "\\end{center}\n" | |
outstr = "\\begin{table}[H]\n" + outstr + "\\end{table}\n" | |
return outstr | |
if __name__ == "__main__": | |
if len(sys.argv) > 1: | |
with open(sys.argv[1], 'r') as fp: | |
text = fp.read() | |
print csv2TeX(text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment