python - 将字符串解析为类层次结构

标签 python parsing syntax pseudocode

假设有一个格式如下的字符串:

"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/

相关文章:

c++ - 使用 boost::spirit 匹配单词

c++ - 使用范围解析运算符时的语法错误

javascript - 在javascript中,是否有检查每一层嵌入对象是否存在的语法快捷方式?

python - 当我使用opencv将图像的路径传递给显示功能时出现此错误

Python 脚本未在调用 pysaunter 的 crontab 中运行

python - Heroku ---> 安装 pip 远程 : AttributeError: module 'pip._vendor.requests' has no attribute 'Session'

Python 3,模块 'itertools' 没有属性 'ifilter'

c# - 使用C#通过div中的内容获取div类

c++ - 为单独解析的句子创建 vector C++

syntax - # 在 Scheme 数字文字中的含义