简体   繁体   中英

PyParsing Parser Alternation

I am using PyParsing to make a parser for my language (N). The syntax is as follows: (name, type, value, next) where next can contain an instance of that syntax itself. My problem is I'm getting a TypeError: unsupported operand type(s) for |: 'str' and 'str' error. I see PyParsing examples with | to support alternation, like in BNF notation.

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 | operator. To create a ParseElement , you can use (for example) Literal("0") . The | operator for ParseElement does accept string arguments, implicitly turning them into Literal s, so you could write:

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

But a much better solution is the more direct:

number = Word("0123456789")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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