PyParsing: Is it possible to globally suppress all Literals?

心已入冬 提交于 2019-12-23 18:43:09

问题


I have a simple data set to parse with lines like the following:

R1 (a/30) to R2 (b/30), metric 30

The only data that I need from the above is as follows:

R1, a, 30, R2, 192.168.0.2, 30, 30

I can parse all of this easily with pyparsing, but I either end up with a bunch of literals in my output, or I have to specifically say Literal(thing).suppress() in my parsing grammar, which gets tiresome.

Ideally, I'd like to write a grammar for the above like:

Word(alphanums) + '(' + Word(alphanums) + '/' + Word(nums) + ... etc.

and have the literal tokens get ignored. Can I say anything like .suppressAllLiterals()?

Notes:

  • new to PyParsing
  • I've read the docs and 5 or 6 examples
  • searched google

Thanks!


回答1:


You can use this method on ParserElement - call it immediately after importing pyparsing:

from pyparsing import ...whatever...
ParserElement.inlineLiteralsUsing(Suppress)

Now all the string literals in your parser will be wrapped in Suppress objects, and left out of the results, rather than the default Literal.

(I will probably make this the default in v3.0, someday, when I can break backward compatibility.)



来源:https://stackoverflow.com/questions/36428652/pyparsing-is-it-possible-to-globally-suppress-all-literals

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