我正在尝试解析一个简单的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
任何人都可以告诉我为什么函数没有得到正确数量的参数吗?
答案 0 :(得分:21)
嗯,setParseAction
的最新版本确实带来了一些额外的魔力,但不幸的是,它牺牲了一些开发的简单性。 setParseAction中的参数检测逻辑现在依赖于在解析操作中引发异常,直到使用正确数量的参数调用它,从3开始并向下运行到0,之后它只是放弃并引发异常你锯。
除非在这种情况下,来自解析操作的异常不是由于参数列表不匹配,而是代码中的实际错误。要获得更好的视图,请在您的解析操作中插入一个通用的try-except:
def keyin_act(instring, loc, tokens):
try:
return set([(tokens.k, set(tokens.vs[0]))])
except Exception as e:
print e
你得到:
unhashable type: 'set'
实际上,创建返回集的列表的第二个元素本身就是一个集合,一个可变容器,因此不能包含在集合中。如果你改为使用冻结集,那么你将获得:
[set([('hi', frozenset([]))])]
为什么冻结空?我建议您将结果名称'vs'的位置更改为:
nestedExpr('{','}', content = delimitedList(value))('vs')
现在通过解析'hi in {1,2,3}'返回的解析结果是:
[set([('hi', frozenset([([1, 2, 3], {})]))])]
这有点混乱,如果我们将此行放在解析操作的顶部,您将看到不同的命名结果实际包含的内容:
print tokens.dump()
我们得到:
['hi', [1, 2, 3]]
- k: hi
- vs: [[1, 2, 3]]
所以'vs'实际指向包含列表的列表。因此,我们可能希望从tokens.vs[0]
而不是tokens.vs
构建我们的集合。现在我们的解析结果如下:
[set([('hi', frozenset([1, 2, 3]))])]
关于语法的其他一些提示:
尝试使用CaselessKeyword而不是CaselessLiteral。关键词是语法关键词的更好选择,因为它们固有地避免将“内部”的前导“输入”误解为语法中的关键词“in”。
不确定从解析操作返回集合的方向 - 对于键值对,元组可能会更好,因为它将保留令牌的顺序。在程序的解析后阶段构建您的键和值集。
对于其他语法调试工具,请查看setDebug
和traceParseAction
装饰器。
答案 1 :(得分:5)
Paul已经解释了根本问题是什么:解析操作引发的TypeError
会混淆pyparsing用于确定解析操作所期望的参数数量的自动方式。
这是我用来避免这种混淆的东西:一个装饰器,如果用较少的参数再次调用该函数,则重新引发由装饰函数抛出的任何TypeError
:
import functools
import inspect
import sys
def parse_action(f):
"""
Decorator for pyparsing parse actions to ease debugging.
pyparsing uses trial & error to deduce the number of arguments a parse
action accepts. Unfortunately any ``TypeError`` raised by a parse action
confuses that mechanism.
This decorator replaces the trial & error mechanism with one based on
reflection. If the decorated function itself raises a ``TypeError`` then
that exception is re-raised if the wrapper is called with less arguments
than required. This makes sure that the actual ``TypeError`` bubbles up
from the call to the parse action (instead of the one caused by pyparsing's
trial & error).
"""
num_args = len(inspect.getargspec(f).args)
if num_args > 3:
raise ValueError('Input function must take at most 3 parameters.')
@functools.wraps(f)
def action(*args):
if len(args) < num_args:
if action.exc_info:
raise action.exc_info[0], action.exc_info[1], action.exc_info[2]
action.exc_info = None
try:
return f(*args[:-(num_args + 1):-1])
except TypeError as e:
action.exc_info = sys.exc_info()
raise
action.exc_info = None
return action
以下是如何使用它:
from pyparsing import Literal
@parse_action
def my_parse_action(tokens):
raise TypeError('Ooops')
x = Literal('x').setParseAction(my_parse_action)
x.parseString('x')
这会给你:
Traceback (most recent call last):
File "test.py", line 49, in <module>
x.parseString('x')
File "/usr/local/lib/python2.7/dist-packages/pyparsing-2.0.2-py2.7.egg/pyparsing.py", line 1101, in parseString
loc, tokens = self._parse( instring, 0 )
File "/usr/local/lib/python2.7/dist-packages/pyparsing-2.0.2-py2.7.egg/pyparsing.py", line 1001, in _parseNoCache
tokens = fn( instring, tokensStart, retTokens )
File "/usr/local/lib/python2.7/dist-packages/pyparsing-2.0.2-py2.7.egg/pyparsing.py", line 765, in wrapper
ret = func(*args[limit[0]:])
File "test.py", line 33, in action
return f(*args[:num_args])
File "test.py", line 46, in my_parse_action
raise TypeError('Ooops')
TypeError: Ooops
将此与您在没有@parse_action
装饰的情况下获得的回溯进行比较:
Traceback (most recent call last):
File "test.py", line 49, in <module>
x.parseString('x')
File "/usr/local/lib/python2.7/dist-packages/pyparsing-2.0.2-py2.7.egg/pyparsing.py", line 1101, in parseString
loc, tokens = self._parse( instring, 0 )
File "/usr/local/lib/python2.7/dist-packages/pyparsing-2.0.2-py2.7.egg/pyparsing.py", line 1001, in _parseNoCache
tokens = fn( instring, tokensStart, retTokens )
File "/usr/local/lib/python2.7/dist-packages/pyparsing-2.0.2-py2.7.egg/pyparsing.py", line 765, in wrapper
ret = func(*args[limit[0]:])
TypeError: my_parse_action() takes exactly 1 argument (0 given)