Converting a python numeric expression to LaTeX(将 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.latex 和 eval:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 python 数值表达式转换为 LaTeX
基础教程推荐
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
