PyParsing:Combine()有什么作用? [英] PyParsing: What does Combine() do?
问题描述
两者之间有什么区别
foo = TOKEN1 + TOKEN2
和
foo = Combine(TOKEN1 + TOKEN2)
谢谢.
更新:根据我的实验,Combine()
似乎是用于终端的,您要在其中构建要匹配的表达式,而普通的+
则是用于非终端的.但是我不确定.
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.
推荐答案
合并有2种效果:
-
它将所有标记连接到一个字符串中
it concatenates all the tokens into a single string
它要求匹配的令牌都必须相邻且没有空格
it requires the matching tokens to all be adjacent with no intervening whitespace
如果创建类似
realnum = Word(nums) + "." + Word(nums)
然后realnum.parseString("3.14")
将返回3个令牌的列表:前导'3','.'和后缀'14'.但是,如果将其包装在Combine中,例如:
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))
然后,realnum.parseString("3.14")
将返回"3.14"(然后您可以使用解析动作将其转换为浮点数).而且由于Combine禁止pyparsing的默认空白在标记之间跳过,因此您不会在答案为3.14是下一个答案"中偶然发现"3.14".
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."
这篇关于PyParsing:Combine()有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!