Re: [Pyparsing] Continue parsing on mismatches
Brought to you by:
ptmcg
From: Paul M. <pt...@au...> - 2010-03-07 17:13:43
|
Donn - See the embedded comments in this code: import pyparsing as PP # just get all the punctuation out of the way dot,comma,open_bracket,close_bracket = map(PP.Suppress,".;()") # I'm finding that complex items like real numbers just work better # using a Regex than Combine'ing Words, Optionals, etc. floater = PP.Regex(r"-?\d+(\.\d*)?([Ee][+-]?\d+)?") floater.setParseAction(lambda toks:float(toks[0])) # define a permissive expression for rotate_command, then do additional # validation in the parse action rotate_command = "rotate" + \ open_bracket + PP.Optional(PP.delimitedList(floater))("args") + \ close_bracket def validate_rotate_args(s,l,tokens): numargs = len(tokens.args) if not(numargs == 1 or numargs == 3): raise PP.ParseException(s,l,"wrong number of args") # convert generic 'args' name to specific field names tokens["angle"] = tokens.args[0] tokens["pivot"] = tokens.args[1:3] del tokens["args"] rotate_command.setParseAction(validate_rotate_args) >From here, you could use scanString or searchString to return just the valid commands: for rotation in rotate_command.searchString(s): print rotation.dump() Gives: ['rotate', 5.0, 5.0, 6.0] - angle: 5.0 - pivot: [5.0, 6.0] ['rotate', 7.0] - angle: 7.0 - pivot: [] The parseAction has detected that "rotate(99,7)" has the wrong number of arguments. There's not really any way to emit a warning while parsing - either the parse matches, or it raises a ParseException. -- Paul |