Python:当使用sympy.parsing.mathematica时,处理变量名中数字后面的字母



我正在使用工具sympy.parsing.mathematica将Mathematica表达式解析为python语法。我希望能够处理包含数字和字母的变量名。

例如,当通过调用mathematica("1 + a23b")解析字符串"1 + a23b + 4"时,我得到输出"a23*b + 1"。我如何表示我希望"a23b"被视为单个变量,从而使上例中的输出变为"a23b + 1"

我试着通过调用mathematica("1 + a23b",{'a23b':'a23b'})传递形式为{'a23b':'a23b'}的字典。然而,这会引发一个带有以下消息ValueError: 'a23b' function form is invalid.ValueError

有什么办法解决这个问题吗?

在SymPy 1.11中,不推荐使用mathematica解析函数:

In [3]: from sympy.parsing.mathematica import mathematica
In [4]: mathematica("1 + a23b")
<ipython-input-4-925ed25e63e8>:1: SymPyDeprecationWarning: 
The ``mathematica`` function for the Mathematica parser is now
deprecated. Use ``parse_mathematica`` instead.
The parameter ``additional_translation`` can be replaced by SymPy's
.replace( ) or .subs( ) methods on the output expression instead.
See https://docs.sympy.org/latest/explanation/active-deprecations.html#mathematica-parser-new
for details.
This has been deprecated since SymPy version 1.11. It
will be removed in a future version of SymPy.
mathematica("1 + a23b")
Out[4]: a₂₃⋅b + 1

相反,建议使用parse_mathematica函数,以您希望的方式处理这种情况:

In [5]: from sympy.parsing.mathematica import parse_mathematica
In [6]: parse_mathematica("1 + a23b")
Out[6]: a23b + 1

最新更新