我正在使用PyParsing为我的语言(N)创建一个解析器。语法如下:(name, type, value, next)
,其中next
可以包含该语法本身的实例。我的问题是我得到了一个TypeError: unsupported operand type(s) for |: 'str' and 'str'
错误。我看到PyParsing示例使用|
来支持交替,如BNF表示法。你知道吗
代码:
from pyparsing import *
leftcol = "["
rightcol = "]"
leftgro = "("
rightgro = ")"
sep = ","+ZeroOrMore(" ")
string = QuotedString('"')
intdigit = ("0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")
number = intdigit + ZeroOrMore(intdigit)
none = Word("none")
value = number | string | collection
collection = leftcol + (value + ZeroOrMore(sep + value)) + rightcol
parser = leftgro + string + sep + string + sep + (value) + sep + (parser | none) + rightgro
print(parser.parseString("""
"""))
"0"
是一个普通的Python字符串,而不是ParseElement
,并且字符串没有任何|
操作符的实现。要创建ParseElement
,可以使用(例如)Literal("0")
。ParseElement
的|
运算符接受字符串参数,隐式地将它们转换为Literal
,因此可以编写:但更好的解决方案是更直接:
相关问题 更多 >
编程相关推荐