Evaluating mathematical expressions in Python

前端 未结 5 1268
小鲜肉
小鲜肉 2020-12-17 18:24

I want to tokenize a given mathematical expression into a parse tree like this:

((3 + 4 - 1) * 5 + 6 * -7) / 2

                          \'/\'
                      


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 19:11

    I don't know of a "pure python" way to do this, that is already implemented for you. However you should check out ANTLR (http://www.antlr.org/) it's an open source parser an lexer and it has an API for a number of languages, including python. Also this website has some great video tutorials that will show you how to do exactly what you are asking. It's a very useful tool to know how to use in general.

提交回复
热议问题