Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyparsing issue

Right now I have just started to use pyparsing to parse simple postfix expressions. At the moment, I got this far:

from pyparsing import *
integer = Word(nums)
op = Word("+-*/^", max=1)
space = Word(" ")
expr = Word(nums)+space+Word(nums)+space+op
parsed = expr.parseString("3 4 *")
print parsed

But when I run it, it prints:

Traceback (most recent call last):
  File "star_parse.py", line 6, in <module>
    parsed = expr.parseString("3 4 *")
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pyparsing-1.5.5-py2.6.egg/pyparsing.py", line 1100, in parseString
    raise exc
pyparsing.ParseException: Expected W:( ) (at char 2), (line:1, col:3)

What am I doing wrong?

like image 741
tekknolagi Avatar asked Dec 30 '25 02:12

tekknolagi


2 Answers

White space is handled by default. There is also the handy oneOf:

from pyparsing import *
integer = Word(nums)
op = oneOf('* + - / ^')
expr = integer + integer + op
parsed = expr.parseString("3 4 *")
print parsed
like image 59
Mark Tolonen Avatar answered Dec 31 '25 14:12

Mark Tolonen


White space is ignored by pyparser. You can explicitly test for whitespace by using the White class.

However the expression you are probably looking for is:

expr = integer + integer + op

http://packages.python.org/pyparsing/pyparsing.pyparsing.White-class.html

like image 44
Dunes Avatar answered Dec 31 '25 15:12

Dunes