有没有针对Python的数学表达式解析器+求值器?在
我不是第一个问这个问题的人,但答案通常指向eval()
。例如,可以这样做:
>>> safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'abs']
>>> safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
>>> s = "2+3"
>>> eval(s, {"__builtins__":None}, safe_dict)
5
但这是not safe:
^{pr2}$另外,使用eval
来解析和计算数学表达式在我看来是错误的。在
我找到了PyMathParser,但它在引擎盖下也使用了eval
,而且没有更好的:
>>> import MathParser
>>> m=MathParser.PyMathParser()
>>> m.expression = s_badbaduser
>>> m.evaluate();
Segmentation fault
有没有一个库可以在不使用Python解析器的情况下解析和计算数学表达式?在
签出Paul McGuire's pyparsing。他编写了通用解析器和grammar for arithmetic expressions:
我建议使用^{} ,然后将解析树白名单。在
这里
^{pr2}$whitelist
可以是类似于:我在这里建立了一些帖子来创建一个评估器类。也使用 eval example我基本上重写成一个类对象。在
以下是一些示例:
^{pr2}$结果
相关问题 更多 >
编程相关推荐