使用pyparsing解析嵌套的函数调用 [英] Parsing nested function calls using pyparsing

查看:93
本文介绍了使用pyparsing解析嵌套的函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用pyparsing来解析以下形式的函数调用:

I'm trying to use pyparsing to parse function calls in the form:

f(x, y)

那很容易.但是,由于它是递归下降的解析器,因此解析起来也应该很容易:

That's easy. But since it's a recursive-descent parser, it should also be easy to parse:

f(g(x), y)

那是我无法获得的.这是一个简化的示例:

That's what I can't get. Here's a boiled-down example:

from pyparsing import Forward, Word, alphas, alphanums, nums, ZeroOrMore, Literal

lparen = Literal("(")
rparen = Literal(")")

identifier = Word(alphas, alphanums + "_")
integer  = Word( nums )

functor = identifier

# allow expression to be used recursively
expression = Forward()

arg = identifier | integer | expression
args = arg + ZeroOrMore("," + arg)

expression << functor + lparen + args + rparen

print expression.parseString("f(x, y)")
print expression.parseString("f(g(x), y)")

这是输出:

['f', '(', 'x', ',', 'y', ')']
Traceback (most recent call last):
  File "tmp.py", line 14, in <module>
    print expression.parseString("f(g(x), y)")
  File "/usr/local/lib/python2.6/dist-packages/pyparsing-1.5.6-py2.6.egg/pyparsing.py", line 1032, in parseString
    raise exc
pyparsing.ParseException: Expected ")" (at char 3), (line:1, col:4)

为什么我的解析器将内部表达式的函子解释为独立标识符?

Why does my parser interpret the functor of the inner expression as a standalone identifier?

推荐答案

arg的定义应与左侧以另一个开头的项目一起排列,因此应优先进行匹配:

The definition of arg should be arranged with the item that starts with another at the left, so it is matched preferentially:

arg = expression | identifier | integer

这篇关于使用pyparsing解析嵌套的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆