3

Imagine the following types of strings:

if ((a1 and b) or (a2 and c)) or (c and d) or (e and f)

Now, I'd like to get the expressions in parentheses, so I wrote a PEG parser with the following grammar:

from parsimonious.grammar import Grammar

grammar = Grammar(
    r"""
    program     = if expr+
    expr        = term (operator term)*
    term        = (factor operator factor) / factor
    factor      = (lpar word operator word rpar) / (lpar expr rpar)

    if          = "if" ws
    and         = "and"
    or          = "or"
    operator    = ws? (and / or) ws?

    word        = ~"\w+"
    lpar        = "("
    rpar        = ")"

    ws          = ~"\s*"
    """)

which parses just fine with

tree = grammar.parse(string)

Now the question arises: how to write a NodeVisitor class for this tree to get only the factors? My problem here is the second branch which can be deeply nested.


I tried with

def walk(node, level = 0):
    if node.expr.name == "factor":
        print(level * "-", node.text)

    for child in node.children:
        walk(child, level + 1)

walk(tree)

but to no avail, really (factors bubble up in duplicates).
Note: This question is based on another one on StackOverflow.

4

2 回答 2

2

我将如何将 ((a1 和 b) 或 (a2 和 c))、(c 和 d) 和 (e 和 f) 作为三个部分?

您可以创建一个访问者,当解析树中的节点是 a 时“侦听” (,其中深度变量增加,当)遇到 a 时,深度变量减少。然后在被调用的匹配括号表达式的方法中,在将深度添加到表达式列表以从访问者返回之前检查深度。

这是一个简单的例子:

from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor

grammar = Grammar(
    r"""
    program     = if expr+
    expr        = term (operator term)*
    term        = (lpar expr rpar) / word

    if          = "if" ws
    and         = "and"
    or          = "or"
    operator    = ws? (and / or) ws?

    word        = ~"\w+"
    lpar        = "("
    rpar        = ")"

    ws          = ~"\s*"
    """)


class ParExprVisitor(NodeVisitor):

    def __init__(self):
        self.depth = 0
        self.par_expr = []

    def visit_term(self, node, visited_children):
        if self.depth == 0:
            self.par_expr.append(node.text)

    def visit_lpar(self, node, visited_children):
        self.depth += 1

    def visit_rpar(self, node, visited_children):
        self.depth -= 1

    def generic_visit(self, node, visited_children):
        return self.par_expr


tree = grammar.parse("if ((a1 and b) or (a2 and c)) or (c and d) or (e and f)")
visitor = ParExprVisitor()

for expr in visitor.visit(tree):
    print(expr)

打印:

((a1 and b) or (a2 and c))
(c and d)
(e and f)
于 2019-04-01T18:38:07.527 回答
1

如果您只想返回每个最外层的因素,return请尽早并且不要下降到其子级。

def walk(node, level = 0):
    if node.expr.name == "factor":
        print(level * "-", node.text)
        return
    for child in node.children:
        walk(child, level + 1)

输出:

----- ((a1 and b) or (a2 and c))
----- (c and d)
------ (e and f)
于 2019-03-31T20:33:08.463 回答