PyParsing: Is it possible to globally suppress all

2019-07-15 09:38发布

问题:

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.)