简体   繁体   English

PyParsing解析器交替

[英]PyParsing Parser Alternation

I am using PyParsing to make a parser for my language (N). 我正在使用PyParsing为我的语言(N)创建解析器。 The syntax is as follows: (name, type, value, next) where next can contain an instance of that syntax itself. 语法如下:( (name, type, value, next) ,其中next可以包含该语法本身的实例。 My problem is I'm getting a TypeError: unsupported operand type(s) for |: 'str' and 'str' error. 我的问题是我收到TypeError: unsupported operand type(s) for |: 'str' and 'str'错误的TypeError: unsupported operand type(s) for |: 'str' and 'str' I see PyParsing examples with | 我看到带有| PyParsing示例 to support alternation, like in BNF notation. 支持交替,例如BNF表示法。

Code: 码:

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" is an ordinary Python string, not a ParseElement , and strings don't have any implementation of the | "0"是普通的Python字符串,而不是ParseElement ,并且字符串没有|任何实现。 operator. 运营商。 To create a ParseElement , you can use (for example) Literal("0") . 要创建ParseElement ,可以使用(例如) Literal("0") The | | operator for ParseElement does accept string arguments, implicitly turning them into Literal s, so you could write: ParseElement运算符确实接受字符串参数,将其隐式地转换为Literal ,因此您可以编写:

intdigit = Literal("0") | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"

But a much better solution is the more direct: 但是更好的解决方案是更直接的:

number = Word("0123456789")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM