将 python 数值表达式转换为 LaTeX

2022-01-24 00:00:00 python latex math

问题描述

我需要使用有效的 python 语法转换字符串,例如:

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

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

并获得等效的 LaTeX:

and get the equivalent LaTeX:

$1+2^{x+y}$

我尝试过 sympy 的 latex 函数,但它处理的是实际表达式,而不是它的字符串形式:

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)$'

但要做到这一点,它需要将 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'))))))))]))

最后但并非最不重要的原因是:我需要生成这些乳胶片段,以便我可以使用 mathjax 在网页中显示它们.

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


解决方案

你可以使用 sympy.latexeval:

s = "1+2**(x+y)"
sympy.latex(eval(s))   # prints '$1 + {2}^{x + y}$'

您仍然必须将变量声明为符号,但如果这确实是个问题,那么编写解析器来执行此操作要比解析所有内容并从头开始生成乳胶要容易得多.

You still have to declare the variables as symbols, but if this is really a problem, it's much easier to write a parser to do this than to parse everything and generate the latex from scratch.

相关文章