简体   繁体   中英

Pyparsing: How do I store a token into a following list/group?

I'm trying to write a parser with pyparsing. Here's a snippit from my grammar definitions:

import pyparsing as pp

Modifier = pp.Word(pp.alphas)
Name = pp.Literal("foobar")
Sentence = pp.Optional(Modifier) + Name + pp.Group(pp.OneOrMore(Modifier))

And here's what happens when I parse a sample string:

>>> print Sentence.parseString("testA FOOBAR testB testC")
['testA', 'FOOBAR', ['testB', 'testC']]

Is there any way to modify my grammar rules above so it pushes the first optional modifier into the following group?

Example:

>>> print MagicSentence.parseString("test A FOOBAR testB testC")
['FOOBAR', ['testA', 'testB', 'testC']]

The most straightforward way to do this is to parse it pretty much as you have done, but add a parse action to Sentence to do the element re-arranging. Something like this:

>>> def moveLeadingItem(tokens):
...     first = tokens[0]
...     del tokens[0]
...     tokens[-1].insert(0,first)
... 
>>> Sentence.setParseAction(moveLeadingItem)
>>> print Sentence.parseString("testA foobar testB testC")
['foobar', ['testA', 'testB', 'testC']]

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