我需要一些代码只在对递归解析器的最外层调用中运行,但是想不出用pyparsing实现这一点的方法。这是我的密码:
from pyparsing import *
from itertools import count
L_PAR, R_PAR, = map(Suppress, '()')
def process_stmt(counter):
"""Closure counts up when nesting occurs"""
def parse_action(tokens):
for t in tokens:
t["count"] = next(counter)
# if not outermost:
t["outermost"] = False
# if outermost:
# t["outermost"] = True
return parse_action
def outermost_true(tokens):
tokens['outermost'] = True
tokens['other'] = True
counter = count(0)
OR_stmt = Forward()
AND_stmt = Group(OneOrMore(Word("XYZ", exact=3)
^ OR_stmt))("AND*")
AND_stmt.setParseAction(process_stmt(counter))
OR_stmt <<= Group(L_PAR
+ OneOrMore(AND_stmt)
+ R_PAR)("OR*")
OR_stmt.setParseAction(process_stmt(counter))
AND_stmt.addParseAction(outermost_true)
data = "(XXXYYY)ZZZ"
AND_stmt.runTests(data)
产生以下结果
(XXXYYY)ZZZ
[[[['XXX', 'YYY']], 'ZZZ']]
- AND: [[[['XXX', 'YYY']], 'ZZZ']]
[0]:
[[['XXX', 'YYY']], 'ZZZ']
- OR: [[['XXX', 'YYY']]]
[0]:
[['XXX', 'YYY']]
- AND: [['XXX', 'YYY']]
[0]:
['XXX', 'YYY']
- count: 0
- outermost: False
- count: 1
- other: True
- outermost: False
- count: 2
- outermost: False
- other: True
- outermost: True
如何将最外层的outermost
属性设置为True
?你知道吗
当我看到你把
outermost
设为True
或False
时,我想我误解了你的意图。重新阅读您的问题,您希望代码只在对递归解析器的最外层调用中运行。正如我在评论中猜测的那样,解决方案是创建一个外部Forward
容器并将解析操作附加到该容器上。以下是您的代码,其中删除了对process_stmt
的所有中间调用,只对包含Forward
的最外层进行了一次调用:它给出:
如果您仍然希望为层次结构的每个级别调用一个解析操作,我修改了process stmt,以便在每次调用时打印其进度:
显示这些中间步骤-更好地可视化每个调用如何将内部级别
outermost
重置为False,将自己的最外层级别重置为True相关问题 更多 >
编程相关推荐