reStructuredTextのsimple tableをtexに変換、ただしmulticolumn, multirowは不可

数式は:math:`hoge`。

#!/usr/bin/python

import sys
import re
rstfile = open(sys.argv[1])

remath = re.compile(r':math:`.*`')
rows = []
for line in rstfile:
    if re.match("^=+$", line.strip().replace(' ', '')):
        rows.append([elem for elem in line.split()])
        eqlens = [len(elem) for elem in line.split()]
        break

num_columns = len(eqlens)

for line in rstfile:
    row = []
    pos = 0
    for i in range(num_columns):
        row.append(line[pos:pos + eqlens[i]].strip())
        pos += eqlens[i] + 1
    rows.append(row)


print """\documentclass[amsmath,amssymb,a4paper]{revtex4}
\\usepackage{amsmath}
\\usepackage{multirow}
\\usepackage[dvipdfm]{graphicx}
\\pagestyle{empty}
\\begin{document}
\\begin{table}"""

print "\\begin{tabular}{%s}" % ("l" * num_columns)

for row in rows:
    is_hline = True
    for elem in row:
        if re.match("^=+$", elem):
            eqlens.append(len(elem))
        else:
            is_hline = False
            break

    if is_hline:
        print "\hline"
    else:
        for i, elem in enumerate(row):
            if ":math:" in elem:
                replstr = "$%s$" % re.findall('`.*`', elem)[0].strip('`')
                print remath.sub(repr(replstr), elem).replace('\'$', '$').replace('$\'', '$'),
            else:
                print elem,
            if i < num_columns - 1:
                print "&",
            else:
                print "\\\\"


print """\\end{tabular}
\\end{table}
\\end{document}"""