I'm new using pyparsing, but I can't find how to solve this quite easy issue. I have (for the moment) a simple grammar, but I can' t find the way to discriminate the result of parsing according the types I defined in my grammar.
Maybe it' d be easier to explain it with an example. Supposing this element:
elem = foo | bar
When I invoke:
elem.parseString("...")
supposing the string matches with my grammar, how can I discriminate if it matches with ' foo' or with ' bar'? I get an instance object of ParseResults with no such metadata.
Thanks in advance.
You could assign a name to them (a convoluted example using Literal):
foo = Literal('foo').setResultsName('foo')
bar = Literal('bar').setResultsName('bar')
grammar = foo | bar
parsed = grammar.parseString('bar foo')
print parsed
# (['bar'], {'bar': [('bar', 0)]})
print parsed.asDict()
# {'bar': 'bar'}
Jon Clements' answer is the correct one, here is just some extra code in support of his post, showing how to use getName()
to detect which term you got:
>>> from pyparsing import Literal, OneOrMore, Group
>>> bar = Literal('bar').setResultsName('BAR')
>>> foo = Literal('foo')('FOO') # using short form
>>> grammar = OneOrMore(Group(foo | bar))
>>> parsed = grammar.parseString('bar foo')
>>> for p in parsed: print p[0], p.getName()
...
bar BAR
foo FOO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With