PyParsing: What does Combine() do?

不想你离开。 提交于 2019-12-06 02:35:19

问题


What is the difference between:

foo = TOKEN1 + TOKEN2

and

foo = Combine(TOKEN1 + TOKEN2)

Thanks.

UPDATE: Based on my experimentation, it seems like Combine() is for terminals, where you're trying to build an expression to match on, whereas plain + is for non-terminals. But I'm not sure.


回答1:


Combine has 2 effects:

  • it concatenates all the tokens into a single string

  • it requires the matching tokens to all be adjacent with no intervening whitespace

If you create an expression like

realnum = Word(nums) + "." + Word(nums)

Then realnum.parseString("3.14") will return a list of 3 tokens: the leading '3', the '.', and the trailing '14'. But if you wrap this in Combine, as in:

realnum = Combine(Word(nums) + "." + Word(nums))

then realnum.parseString("3.14") will return '3.14' (which you could then convert to a float using a parse action). And since Combine suppresses pyparsing's default whitespace skipping between tokens, you won't accidentally find "3.14" in "The answer is 3. 14 is the next answer."



来源:https://stackoverflow.com/questions/2940489/pyparsing-what-does-combine-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!