In PyParsing, how to use Combine() with a non-default joinString

时间:2017-07-17 15:26:28

标签: python pyparsing

I'm trying to refactor the version_name in the following parsing expression:

In [1]: from pyparsing import *

In [2]: version_code = "(" + Word(nums)("version_code") + ")"

In [3]: version_name = OneOrMore(~version_code + Word(printables)).setParseActio
   ...: n(lambda s,l,t: " ".join(t))("version_name")

In [4]: expression = version_name + version_code

In [5]: result = expression.parseString("1.0 beta (10)")

In [6]: result.asDict()
Out[6]: {'version_code': '10', 'version_name': '1.0 beta'}

Instead of using .setParseAction(lambda s,l,t: " ".join(t)), I would like to use Combine(). However, if I try to replace version_name with

In [7]: version_name = Combine(OneOrMore(~version_code + Word(printables)), join
   ...: String=" ")("version_name")

then upon re-running the test,

In [8]: expression = version_name + version_code

In [9]: result = expression.parseString("1.0 beta (10)")

I get a

ParseException: Expected "(" (at char 4), (line:1, col:5)

It seems like the parser is stopping with parsing the version_name after the 1.0 and not after 1.0 beta as intended. Is there a way to refactor this with Combine() such that it still works?

1 个答案:

答案 0 :(得分:0)

根据PaulMcG的评论,我在adjacent=False的构造函数中添加了Combine()

In [1]: from pyparsing import *

In [2]: version_code = "(" + Word(nums)("version_code") + ")"

In [3]: version_name = Combine(OneOrMore(~version_code + Word(printables)), joinString=" ", adjacent=False)("version_name")

In [4]: expression = version_name + version_code

In [5]: result = expression.parseString("1.0 beta (10)")

In [6]: result.asDict()
Out[6]: {'version_code': '10', 'version_name': '1.0 beta'}

version_name现在根据需要包含两个单词('1.0 beta')。