问题
I'm trying to implement something in ply, which I'm very new to, based on what I have done in pyparsing, which I'm also quite new to. How can I write a simple nesting search such as this:
thecontent = pyparsing.Word(pyparsing.alphanums) | '&' | '|'
parens = pyparsing.nestedExpr( '(', ')', content=thecontent)
By using PLY?
回答1:
What you have written in pyparsing does not translate well to PLY because, well, it's barely even a parser. nestedExpr
is a helper for quickly defining an expression of the form "I don't really know what's in this, but it's surrounded by ()
's (or {}
's or []
's or whatever), and they can be nested". Really handy to parse a '{}'-delimited language like C, to define a simple function definition as type_spec + identifier + parameter_spec + nestedExpr('{', '}')
. Given that you are defining your content to include '&' and '|' operators, it sounds like you really want to parse a boolean expression, including support for parenthetical grouping to override precedence of operations.
The simpleBool.py example on the pyparsing wiki's Examples page shows some test cases and expressions to support boolean expression parsing. BUT it still uses a helper method, infixNotation
, which hides much of the parser definition steps, so again, will be difficult to translate to PLY directly. I reference this example though, because it may help you clarify just what is involved in parsing boolean expressions (including parsing boolean literals like "True", "False", etc., and maybe add support for a "not" operator). Also, it will give you a bunch of free test cases - help yourself!
To see a more explicit grammar that is akin to what PLY will expect, look at pyparsing's fourFn.py example. It predates the infixNotation
helper, and so builds up the various operation precedences explicitly. (The elegance of this form of implementation of arithmetic operator precedence is largely what got me interested in parsing applications in the first place.)
来源:https://stackoverflow.com/questions/40864117/how-do-i-implement-this-in-ply-given-how-pyparsing-works