deo*_*ian 16 python parsing pyparsing
我正在尝试解析一个简单的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
Run Code Online (Sandbox Code Playgroud)
目前,"语法"非终结符只是一个存根,我最终会为键添加可嵌套的连词和析取,以便可以解析这样的搜索:
a = 1, b = 2 , c in {1,2,3} | d = 4, ( e = 5 | e = 2, (f = 3, f = 4))
Run Code Online (Sandbox Code Playgroud)
但就目前而言,我无法理解pyparsing如何调用我的setParseAction函数.我知道在传递了多少个参数方面有一些魔力,但是我得到一个错误,其中没有任何参数传递给函数.所以目前,如果我这样做:
grammar.parseString('hi in {1,2,3}')
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
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)
Run Code Online (Sandbox Code Playgroud)
从traceback中可以看出,我使用的是python2.6,而pyparsing是1.5.6
谁能让我深入了解为什么函数没有得到正确数量的参数?
Pau*_*McG 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
Run Code Online (Sandbox Code Playgroud)
你得到:
unhashable type: 'set'
Run Code Online (Sandbox Code Playgroud)
事实上,您创建返回集的列表的第二个元素本身就是一个集合,一个可变容器,因此无法包含在集合中.如果你改为使用冷冻集代替,那么你会得到:
[set([('hi', frozenset([]))])]
Run Code Online (Sandbox Code Playgroud)
为什么冻结空?我建议您将结果名称'vs'的位置更改为:
nestedExpr('{','}', content = delimitedList(value))('vs')
Run Code Online (Sandbox Code Playgroud)
现在解析'hi in {1,2,3}'返回的解析结果是:
[set([('hi', frozenset([([1, 2, 3], {})]))])]
Run Code Online (Sandbox Code Playgroud)
这是一个混乱,如果我们将此行放在您的解析操作的顶部,您将看到不同的命名结果实际包含的内容:
print tokens.dump()
Run Code Online (Sandbox Code Playgroud)
我们得到:
['hi', [1, 2, 3]]
- k: hi
- vs: [[1, 2, 3]]
Run Code Online (Sandbox Code Playgroud)
因此'vs'实际指向包含列表的列表.所以我们可能想要构建我们的集合tokens.vs[0]
,而不是tokens.vs
.现在我们的解析结果如下:
[set([('hi', frozenset([1, 2, 3]))])]
Run Code Online (Sandbox Code Playgroud)
关于语法的一些其他提示:
而不是CaselessLiteral,尝试使用CaselessKeyword.关键字是语法关键词的更好选择,因为它们固有地避免将"内部"的前导"输入"误认为语法中的关键词"in".
不确定从解析操作返回集合的方向 - 对于键值对,元组可能会更好,因为它将保留令牌的顺序.在程序的解析后阶段构建您的键和值集.
对于其他语法调试工具,请查看setDebug
和traceParseAction
装饰器.
保罗已经解释了根本问题是什么: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
Run Code Online (Sandbox Code Playgroud)
以下是如何使用它:
from pyparsing import Literal
@parse_action
def my_parse_action(tokens):
raise TypeError('Ooops')
x = Literal('x').setParseAction(my_parse_action)
x.parseString('x')
Run Code Online (Sandbox Code Playgroud)
这给你:
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
Run Code Online (Sandbox Code Playgroud)
将此与没有@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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2488 次 |
最近记录: |