【发布时间】:2015-07-17 02:31:25
【问题描述】:
我正在尝试创建一个计算器,不是用于数字,而是用于集合运算。 为了说明这个概念,假设您有一个包含两列的文件。
keyword, userid
hello , john
hello , alice
world , alice
world , john
mars , john
pluto , dave
目标是读入类似的表达式
[hello]
并返回具有该关键字的用户集。例如
[hello] -> ['john','alice']
[world] - [mars] -> ['alice'] // the - here is for the difference operation
[world] * [mars] -> ['john','alice'] // the * here is for the intersection operation
[world] + [pluto] -> ['john','alice','dave'] // the + here is for union operation
我使用python中的plyplus模块生成以下语法来解析这个需求。语法如下图
Grammar("""
start: tprog ;
@tprog: atom | expr u_symbol expr | expr i_symbol expr | expr d_symbol | expr | '\[' tprog '\]';
expr: atom | '\[' tprog '\]';
@atom: '\[' queryterm '\]' ;
u_symbol: '\+' ;
i_symbol: '\*' ;
d_symbol: '\-' ;
queryterm: '[\w ]+' ;
WS: '[ \t]+' (%ignore);
""")
但是,我无法在网络上找到任何好的链接来将解析后的输出提升到下一个级别,我可以逐步评估解析后的输出。我知道我需要将它解析为某种语法树并定义函数以递归地应用于每个节点及其子节点。任何帮助表示赞赏。
【问题讨论】:
-
以下是为python中的算术表达式创建递归下降解析器。大概,您可以简单地定义自己的语法/标记? blog.erezsh.com/…
-
我已经浏览过那个网站,但是很难将算术运算映射到集合运算
标签: python parsing grammar ply python-plyplus