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

查看:172
本文介绍了将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的乳胶功能,但是它处理实际的表达式,而不是它的字符串形式:

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天全站免登陆