Checking the type of results using a run

I am using pyparsing, but I can not find how to solve this rather easy problem. I have (at the moment) a simple grammar, but I canโ€™t find a way to recognize the result of parsing by the types defined in my grammar.

It may be easier to explain this with an example. Assume this item:

elem = foo | bar 

When I call:

 elem.parseString("...") 

Suppose a string matches my grammar, how can I distinguish if it matches "foo" or "bar"? I get an instance of the ParseResults object without such metadata.

Thanks in advance.

+7
source share
2 answers

You can give them a name (minimized 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'} 
+4
source

John Clements' answer is correct, here is just some additional code to support his post, showing how to use getName() to determine which one 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 
+4
source

All Articles