Search code examples
pythonfilelatexevalfractions

Reading LaTeX with python eval()


I have files with formulas for sums of powers written in LaTeX. I'm looking for an easy way to translate this into something that eval() can use (I know this is a bad solution but it will only be run locally and read from these specific files). Is there some sort of LaTeX to math translator that can be used? Perhaps some other solution? Example file:

\[\sum_{k=1}^xk^0=x\]
\[\sum_{k=1}^x k^{1}= \frac{x^{1}}{2} + \frac{x^{2}}{2}\]
\[\sum_{k=1}^x k^{2}= \frac{x^{1}}{6} + \frac{x^{2}}{2} + \frac{x^{3}}{3}\]
\[\sum_{k=1}^x k^{3}= \frac{x^{2}}{4} + \frac{x^{3}}{2} + \frac{x^{4}}{4}\]
\[\sum_{k=1}^x k^{4}= \frac{x^{1}}{30} + \frac{x^{3}}{3} + \frac{x^{4}}{2} + \frac{x^{5}}{5}\]
\[\sum_{k=1}^x k^{5}= \frac{x^{2}}{12} + \frac{5x^{4}}{12} + \frac{x^{5}}{2} + \frac{x^{6}}{6}\]

Solution

  • use sympy the library for symbolic manipulation. To make the code work you need extra packages as well. parse_latex will turn the latex code into sympy object, docs.

    import sympy
    from sympy.parsing.latex import parse_latex
    
    latex = """\[\sum_{k=1}^xk^0=x\]
    \[\sum_{k=1}^x k^{1}= \frac{x^{1}}{2} + \frac{x^{2}}{2}\]
    \[\sum_{k=1}^x k^{2}= \frac{x^{1}}{6} + \frac{x^{2}}{2} + \frac{x^{3}}{3}\]
    \[\sum_{k=1}^x k^{3}= \frac{x^{2}}{4} + \frac{x^{3}}{2} + \frac{x^{4}}{4}\]
    \[\sum_{k=1}^x k^{4}= \frac{x^{1}}{30} + \frac{x^{3}}{3} + \frac{x^{4}}{2} + \frac{x^{5}}{5}\]
    \[\sum_{k=1}^x k^{5}= \frac{x^{2}}{12} + \frac{5x^{4}}{12} + \frac{x^{5}}{2} + \frac{x^{6}}{6}\]"""
    
    eqs = map(parse_latex, latex.split('\n'))
    
    for eq in eqs:
        print(eq)