pyparsing问题

时间:2011-06-14 06:35:07

标签: python parsing expression pyparsing postfix-operator

现在我刚开始使用pyparsing来解析简单的后缀表达式。目前,我做到了这一点:

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

但是当我运行它时,会打印出来:

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)

我做错了什么?

2 个答案:

答案 0 :(得分:6)

默认情况下处理空格。还有方便的oneOf

from pyparsing import *
integer = Word(nums)
op = oneOf('* + - / ^')
expr = integer + integer + op
parsed = expr.parseString("3 4 *")
print parsed

答案 1 :(得分:4)

pyparser忽略了空格。您可以使用White类显式测试空白。

然而,您可能正在寻找的表达方式是:

expr = integer + integer + op

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