Python中PEG解析器的NodeVisitor类
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python中PEG解析器的NodeVisitor类,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2179字,纯文字阅读大概需要4分钟。
内容图文
![Python中PEG解析器的NodeVisitor类](/upload/InfoBanner/zyjiaocheng/670/e5c1d6acee3640cfb11efee798386e7b.jpg)
想象一下以下类型的字符串:
if ((a1 and b) or (a2 and c)) or (c and d) or (e and f)
现在,我想将表达式放在括号中,因此我编写了具有以下语法的PEG解析器:
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*"
""")
可以很好地解析
tree = grammar.parse(string)
现在出现了问题:如何为此树编写NodeVisitor类以仅获取因素?我的问题是可以深度嵌套的第二个分支.
我尝试过
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)
但实际上没有任何结果(因素重复出现).
注意:此问题基于StackOverflow上的another one.
解决方法:
How would I go about it to get ((a1 and b) or (a2 and c)), (c and d) and (e and f) as three parts?
您可以创建一个访问者,当解析树中的一个节点是一个(侦听器中,深度变量增加,而遇到)时,访问者“侦听”,该深度变量被减小.然后,在与括号表达式匹配的调用方法中,在将深度添加到表达式列表以从访问者返回之前,先检查深度.
这里是一个简单的例子:
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)
内容总结
以上是互联网集市为您收集整理的Python中PEG解析器的NodeVisitor类全部内容,希望文章能够帮你解决Python中PEG解析器的NodeVisitor类所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。