Python解析数学文本表达式

Python parse mathematical text expression

我想知道是否有人知道一个很好的 python 库来评估基于文本的数学表达式。例如,

>>> evaluate("Three plus nine")
12

>>> evaluate("Eight + two")
10

我见过人们对字符串中的数值和运算符所做的类似示例。 One method used eval to compute the literal value of the expression. And another method of doing this used regex to parse the text.

如果没有现有的库可以很好地处理这个问题,我可能最终会为此结合使用正则表达式和评估技术。我只是想确认目前还没有这样的东西。

您可以尝试 pyparsing, which does general recursive descent parsing. In fact, here 与您的第二个示例非常接近。

关于您的其他建议。