简体   繁体   English

将字符串转换为SymPy表达式?

[英]Convert a string to a SymPy expression?

I'm trying to convert a string to a SymPy expression. 我正在尝试将字符串转换为SymPy表达式。 I've tried sympify() and parse_expr() but both are returning errors. 我试过sympify()parse_expr()但是都返回错误。 How can I correct these errors or workaround them using an alternative method? 如何纠正这些错误或使用替代方法解决这些错误? I'm using Python 3.4. 我正在使用Python 3.4。

from sympy import *
s = 'C+O*2'
expr = sympify(s)

from sympy.parsing.sympy_parser import parse_expr
s = 'C+O*2'
expr = parse_expr(s)

Both of these functions return the following error: 这两个函数均返回以下错误:

File "C:\...\sympy\core\mul.py", line 182, in flatten
    r, b = b.as_coeff_Mul()

TypeError: as_coeff_Mul() missing 1 required positional argument: 'self'

As the documentation for sympify explains: 如症状文档所述:

[T]he O is interpreted as the Order object (used with series) and it raises an error when used improperly[.] [ O ] O被解释为Order对象(与series一起使用),如果使用不当,则会引发错误。

It proposes some workarounds, and the one I prefer is to use the clash locals: 它提出了一些解决方法,我更喜欢使用冲突的本地方法:

>>> from sympy.abc import _clash1
>>> sympify("C+O*2", locals=_clash1)
C + 2*O

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM