假设有一个格式如下的字符串:
"2 + 3 * (5 + 2) * -1 - 2"
(只是一个例子,不一定是算术语法)
被解析为基于类的层次结构
add(2,sub(mul(mul(3,add(5,2)),-1),2))
我正在寻找一种有效的方法来进行此解析。目前的问题是我不确定这种解析叫什么。因此我找不到正确的来源/引用文献。有什么建议吗?
最佳答案
如果这是合法的 python 表达式,您可以使用 ast module ,特别是ast.parse
:
>>> import ast
>>> s = ast.parse("2 + 3 * (5 + 2) * -1 - 2")
>>> ast.dump(s)
'Module(body=[Expr(value=BinOp(left=BinOp(left=Num(n=2), op=Add(), right=BinOp(l
eft=BinOp(left=Num(n=3), op=Mult(), right=BinOp(left=Num(n=5), op=Add(), right=N
um(n=2))), op=Mult(), right=Num(n=-1))), op=Sub(), right=Num(n=2)))])'
使用 ast.Visitor
你可以遍历这棵树。
关于python - 将字符串解析为类层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17346549/