PyParsing 解析器交替
PyParsing Parser Alternation
我正在使用 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
s,所以你可以这样写:
intdigit = Literal("0") | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
但更好的解决方案是更直接:
number = Word("0123456789")
我正在使用 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
s,所以你可以这样写:
intdigit = Literal("0") | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
但更好的解决方案是更直接:
number = Word("0123456789")