将 python 数值表达式转换为 LaTeX [英] Converting a python numeric expression to LaTeX

查看:22
本文介绍了将 python 数值表达式转换为 LaTeX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用有效的 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.

这篇关于将 python 数值表达式转换为 LaTeX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆