Gunther
Gunther

Reputation: 2645

Python parse mathematical text expression

I was wondering if anyone knew of a good python library for evaluation text-based mathematical expressions. So for example,

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

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

I've seen similar examples that people have done for numeric values and operators in a string. One method used eval to compute the literal value of the expression. And another method of doing this used regex to parse the text.

If there isn't an existing library that handles this well I will probably end up using a combination of the regex and eval techniques for this. I just want to confirm that there isn't already something like this already out there.

Upvotes: 0

Views: 171

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76297

You could try pyparsing, which does general recursive descent parsing. In fact, here is something quite close to your second example.

About your other suggestions.

Upvotes: 3

Related Questions