Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type checking on results with pyparsing

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.

like image 582
wikier Avatar asked Oct 26 '12 09:10

wikier


2 Answers

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'}
like image 167
Jon Clements Avatar answered Nov 14 '22 22:11

Jon Clements


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
like image 34
PaulMcG Avatar answered Nov 14 '22 21:11

PaulMcG