Converting a python numeric expression to LaTeX

Viewed 21372

I need to convert strings with valid python syntax such as:

'1+2**(x+y)'

and get the equivalent LaTeX:

$1+2^{x+y}$

I have tried sympy's latex function but it processes actual expression, rather than the string form of it:

>>> latex(1+2**(x+y))
'$1 + 2^{x + y}$'
>>> latex('1+2**(x+y)')
'$1+2**(x+y)$'

but to even do this, it requires x and y to be declared as type "symbols".

I want something more straight forward, preferably doable with the parser from the compiler module.

>>> compiler.parse('1+2**(x+y)')
Module(None, Stmt([Discard(Add((Const(1), Power((Const(2), Add((Name('x'), Name('y'))))))))]))

Last but not least, the why: I need to generate those latex snipptes so that I can show them in a webpage with mathjax.

6 Answers

To render @Geoff Reedy latex format text. We could use matplotlib.

exp = py2tex('1**x+y')
import matplotlib.pyplot as plt
text = exp

plt.text(0.36, 0.5, r"$%s$" %text, fontsize=24)
ax = plt.gca()
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)

plt.show()

enter image description here

Related