gregbanks / python-tabulate

fork of https://bitbucket.org/astanin/python-tabulate
MIT License
178 stars 14 forks source link

Latex format with math mode label #5

Closed caiofcm closed 6 years ago

caiofcm commented 7 years ago

I need to create latex formatted tables from python code. I save the tabulate returning string to a .tex file and direct include them to a parent .tex file (with the appropriated packages).

table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
      ["Moon",1737,73.5],["Mars",3390,641.85]]
headers=["Planet",r"$\theta$ ($km^2$)", r"mass ($\cdot 10^{29}$kg)"]
tabulated = tabulate(table, headers=(headers), tablefmt="latex")
print(tabulated)

Result:

\begin{tabular}{lrr}
\hline
Planet   &   \$\textbackslash{}theta\$ (\$km\^{}2\$) &   mass (\$\textbackslash{}cdot 10\^{}\{29\}\$kg) \\
\hline
Sun      &              696000 &                 1.9891e+09 \\
Earth    &                6371 &              5973.6        \\
Moon     &                1737 &                73.5        \\
Mars     &                3390 &               641.85       \\
\hline
\end{tabular}

Thus, this procedure does not compile without a change in the string format.

I solve this issue using regex to replace unwanted characters:

def convert2LatexString(s):
  r = r'(\^\{\})'; s = re.sub(r, "^", s)
  s = re.sub(r'\\([\$\_\{\}\^])', r'\1', s)
  s = re.sub(r'(\\textbackslash{})', r'\\', s)
  return s

Converted string:

\begin{tabular}{lrr}
\hline
Planet   &   $\theta$ ($km^2$) &   mass ($\cdot 10^{29}$kg) \\
\hline
Sun      &              696000 &                 1.9891e+09 \\
Earth    &                6371 &              5973.6        \\
Moon     &                1737 &                73.5        \\
Mars     &                3390 &               641.85       \\
\hline
\end{tabular}

This converted string I can save and direct include via \include{filename.tex} in my parent .tex file.

My question is if there is a more robust approach to get the appropriated formatted latex string, since I am not an expert on python/string handling.

Thank you

AdityaMayukhSom commented 2 weeks ago

I myself am getting this error. If there are any inbuilt solution into tabulate, I would like to know that. Thanks in advance.