3

私はpyparsingでパーサーを書こうとしています。これが私の文法定義の抜粋です。

import pyparsing as pp

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

サンプル文字列を解析すると、次のようになります。

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

上記の文法規則を変更して、最初のオプションの修飾子を次のグループにプッシュする方法はありますか?

例:

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

1 に答える 1

2

これを行う最も簡単な方法は、これまでとほぼ同じように解析することですが、解析アクションをSentenceに追加して、要素の再配置を行います。このようなもの:

>>> 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']]
于 2012-07-20T21:50:17.567 に答える