我正在使用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("""
"""))发布于 2017-08-29 19:44:44
"0"是一个普通的Python,而不是一个ParseElement,并且字符串没有任何|操作符的实现。要创建ParseElement,可以使用(例如) Literal("0")。用于|的ParseElement操作符确实接受字符串参数,并隐式地将它们转换为Literal,这样您就可以编写:
intdigit = Literal("0") | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"但是一个更好的解决方案是更直接的:
number = Word("0123456789")https://stackoverflow.com/questions/45944304
复制相似问题