如何使用pyparsing解析带有撇号的语言?

约翰·劳伦斯·阿斯普登

我正在尝试使用pyparsing解析一种带有撇号的小语言,一切都很好,直到突然之间我开始收到无法调试的神秘错误。

我已经将解析器缩减到了导致错误的最小程度:

作为我要尝试执行的操作的示例,请考虑一种语言,其中有一个语言,并嵌套了一个语言列表。

例如 1(11)1(1((11)1))

可以这样解析:

from pyparsing import *

sound=Regex(r"1")
beat=sound ^ nestedExpr(content=sound)
tune=OneOrMore(beat)

print(tune.parseString("1"))
print(tune.parseString("11"))
print(tune.parseString("(1)"))
print(tune.parseString("(1(1))"))

但是,如果我尝试添加撇号,则基本单位'1改为:

例如 '1('1'1)'1('1(('1'1)'1))

sound=Regex(r"'1")
beat=sound ^ nestedExpr(content=sound)
tune=OneOrMore(beat)

#These all work as expected

print(tune.parseString("'1"))
print(tune.parseString("'1'1"))
print(tune.parseString("('1)"))

#but
print(tune.parseString("('1('1))"))

导致异常

pyparsing.ParseException: Expected {Re:("'1") ^ nested () expression}, found '1'  (at char 5), (line:1, col:6)

谁能告诉我如何制作像第一个第二个例子中工作,因此由第一个接受任何字符串将被替换每个之后的第一个接受1'1

宫城先生

nestedExpr的预设值为ignoreExpr=quotedString这将尝试匹配'引号作为引号。通过设置禁用它ignoreExpr=None

>>> sound=Regex(r"'1")
>>> beat=sound ^ nestedExpr(content=sound, ignoreExpr=None)
>>> tune=OneOrMore(beat)
>>> print(tune.parseString("('1('1))"))
[["'1", ["'1"]]]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章