其他分享
首页 > 其他分享> > pyparsing知道解析时递归表达式的深度吗?

pyparsing知道解析时递归表达式的深度吗?

作者:互联网

我喜欢使用pyarsing定义parseAction的功能,但是我遇到了特定用例的障碍.接受输入字符串和以下简单语法:

from pyparsing import *

line = "[[one [two [three] two [three [four]]] one] zero]"
token = Word(alphas)

# Define the simple recursive grammar
grammar = Forward()
nestedBrackets = nestedExpr('[', ']', content=grammar) 
grammar << (token | nestedBrackets)

P = grammar.parseString(line)
print P

我希望结果是:

[('one',1), [('two',2), [('three',3)], ('two',2), [('three',3), [('four',4)]]] one], ('zero',0)]

即解析每个令牌并返回带有令牌和深度的元组.我知道可以在解析后完成,但是我想知道是否可以使用parseAction进行解析.这样我对全局变量的不正确尝试:

# Try to count the depth
counter = 0
def action_token(x):
    global counter
    counter += 1
    return (x[0],counter)
token.setParseAction(action_token)

def action_nest(x):
    global counter
    counter -= 1
    return x[0]
nestedBrackets.setParseAction(action_nest)

给予:

[('one', 1), ('two', 2), ('three', 3), ('two', 3), ('three', 4), ('four', 5), ('one', 3), ('zero', 3)]

解决方法:

执行此操作(剩下的一切都保留):

def openB(s, l, t):
    global count
    count += 1
def closeB(s, l, t):
    global count
    count -= 1

opener = Literal("[").setParseAction(openB)
closer = Literal("]").setParseAction(closeB)

nestedBrackets = nestedExpr(opener, closer, content=grammar) 

问题在于,嵌套不取决于匹配的嵌套组的数量,而是取决于匹配的开放式括号的数量与匹配的封闭式括号的数量.因此,您需要在分析打开/关闭方括号时而不是在分析组时调整计数.因此,您需要在组定界符而不是组本身上设置parseAction.

同样,您的示例嵌套了一层(至少在我看来是这样). “零”实际上应该是1,因为它在括号的一级内部,同样,其他所有内容都应上移一级.如果您确实希望最外面的“零”具有零级,依此类推,则需要初始化数到-1.

标签:pyparsing,python,recursion
来源: https://codeday.me/bug/20191101/1981251.html