我正在尝试解析一个简单的 key = value 查询语言。我实际上已经用一个巨大的怪物解析器完成了它,然后我再通过它来清理解析树。我想做的是从下到上进行干净的解析,其中包括使用 (key,val) 对的集合以便消除冗余对等。虽然我之前让它工作过,但我不觉得就像我完全理解为什么 pyparsing 会以这种方式运行一样,所以我做了很多工作等,有点与谷物作斗争。
目前,这是我的“简化”解析器的开始:
from pyparsing import *
bool_act = lambda t: bool(t[0])
int_act = lambda t: int(t[0])
def keyval_act(instring, loc, tokens):
return set([(tokens.k, tokens.v)])
def keyin_act(instring, loc, tokens):
return set([(tokens.k, set(tokens.vs))])
string = (
Word(alphas + '_', alphanums + '_')
| quotedString.setParseAction( removeQuotes )
)
boolean = (
CaselessLiteral('true')
| CaselessLiteral('false')
)
integer = Word(nums).setParseAction( int_act )
value = (
boolean.setParseAction(bool_act)
| integer
| string
)
keyval = (string('k') + Suppress('=') + value('v')
).setParseAction(keyval_act)
keyin = (
string('k') + Suppress(CaselessLiteral('in')) +
nestedExpr('{','}', content = delimitedList(value)('vs'))
).setParseAction(keyin_act)
grammar = keyin + stringEnd | keyval + stringEnd
目前,“语法”非终结符只是一个存根,我最终会在键中添加可嵌套的连词和析取词,以便可以解析这样的搜索:
a = 1, b = 2 , c in {1,2,3} | d = 4, ( e = 5 | e = 2, (f = 3, f = 4))
不过,就目前而言,我无法理解 pyparsing 如何调用我的 setParseAction 函数。我知道在传递多少个参数方面有一些魔力,但是我收到一个错误,根本没有参数传递给函数。所以目前,如果我这样做:
grammar.parseString('hi in {1,2,3}')
我收到此错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/site-packages/pyparsing.py", line 1021, in parseString
loc, tokens = self._parse( instring, 0 )
File "/usr/lib/python2.6/site-packages/pyparsing.py", line 894, in _parseNoCache
loc,tokens = self.parseImpl( instring, preloc, doActions )
File "/usr/lib/python2.6/site-packages/pyparsing.py", line 2478, in parseImpl
ret = e._parse( instring, loc, doActions )
File "/usr/lib/python2.6/site-packages/pyparsing.py", line 894, in _parseNoCache
loc,tokens = self.parseImpl( instring, preloc, doActions )
File "/usr/lib/python2.6/site-packages/pyparsing.py", line 2351, in parseImpl
loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
File "/usr/lib/python2.6/site-packages/pyparsing.py", line 921, in _parseNoCache
tokens = fn( instring, tokensStart, retTokens )
File "/usr/lib/python2.6/site-packages/pyparsing.py", line 675, in wrapper
return func(*args[limit[0]:])
TypeError: keyin_act() takes exactly 3 arguments (0 given)
从回溯中可以看出,我使用的是 python2.6,而 pyparsing 是 1.5.6
谁能给我一些关于为什么函数没有得到正确数量的参数的见解?