Skip to content

Instantly share code, notes, and snippets.

@c-w
Created March 20, 2014 22:13
Show Gist options
  • Save c-w/9675072 to your computer and use it in GitHub Desktop.
Save c-w/9675072 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import re
ARQ_COL = '|'
ARQ_HLINE = '-'
ARQ_HHLINE = '='
TEX_HLINE = '\\hline'
TEX_COL = '&'
TEX_EOL = '\\\\'
def get_ncols(lines):
for line in (l.strip() for l in lines):
ncols = line.strip(ARQ_COL).count(ARQ_COL)
if ncols != 0:
return ncols + 1
return 1
def hline():
print TEX_HLINE
def is_hline(line):
return line == ARQ_HLINE * len(line)
def hhline():
print TEX_HLINE, TEX_HLINE
def is_hhline(line):
return line == ARQ_HHLINE * len(line)
def row(line, translate=[('"', '')]):
def camelCase(s):
chars = []
for i, char in enumerate(s):
if char.isspace():
chars.append(char)
else:
chars.append(char.upper())
chars.extend(s[i+1:])
break
return ''.join(chars)
def snake2camel(s):
tokens = (tok for tok in s.split('_') if tok)
return ' '.join(map(camelCase, tokens))
for source, target in translate:
line = re.sub(re.escape(source), target, line)
line = re.sub(' *', ' ', line)
line = re.sub('&', '\&', line)
line = ARQ_COL.join(map(snake2camel, line.split(ARQ_COL)))
print re.sub(re.escape(ARQ_COL), TEX_COL, line.strip(ARQ_COL)) + TEX_EOL
def start_table(ncols, colstyle='c|'):
print '\\begin{table}'
print '\\centering'
print '\\begin{tabular}{|l|%s}' % (colstyle * (ncols - 1))
def end_table():
print '\\end{tabular}'
print '\\caption{}'
print '\\label{}'
print '\\end{table}'
def convert_lines(lines):
lines = list(lines)
start_table(ncols=get_ncols(lines))
for line in (l.strip() for l in lines):
if is_hline(line):
hline()
elif is_hhline(line):
hhline()
else:
row(line)
end_table()
if __name__ == '__main__':
import fileinput
convert_lines(fileinput.input())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment