py解析问题

发布于 2024-11-15 07:39:45 字数 685 浏览 4 评论 0原文

现在我刚刚开始使用 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)

我做错了什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

虚拟世界 2024-11-22 07:39:45

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

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

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
丶视觉 2024-11-22 07:39:45

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

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

expr = integer + integer + op

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文