是否有另一种设置解析操作的方法,而不是直接在operatorPrecedence
进行pyparsing?
我希望在此示例中的其他位置定义action
。
expr = pp.operatorPrecedence(condition, [
(not_, 1, pp.opAssoc.RIGHT, action),
(and_, 2, pp.opAssoc.LEFT, action),
(or_, 2, pp.opAssoc.LEFT, action),
])
我尝试了and_.setParseAction(action)
,但这并没有获得2个条件参数。 expr.setParseAction(action)
也不起作用。
答案 0 :(得分:0)
A wise man once said,“每个编程问题都可以通过添加另一个间接层来解决。”所以我给你OperParseActionHolder类:
class OperParseActionHolder(object):
def __init__(self):
# initialize with a do-nothing parse action
self.fn = lambda s,l,t: None
def __call__(self, s, l, t):
return self.fn(s,l,t)
notParseAction = OperParseActionHolder()
andParseAction = OperParseActionHolder()
orParseAction = OperParseActionHolder()
expr = pp.operatorPrecedence(condition, [
(not_, 1, pp.opAssoc.RIGHT, notParseAction),
(and_, 2, pp.opAssoc.LEFT, andParseAction),
(or_, 2, pp.opAssoc.LEFT, orParseAction),
])
# before calling expr.parseString
notParseAction.fn = theRealParseActionToCallForNot
andParseAction.fn = theRealParseActionToCallForAnd
orParseAction.fn = theRealParseActionToCallForOr