我正在尝试使用PyParsing在Python中解析类似于CLIPS的语法.
我遇到问题的那段代码是:
import pyparsing as pp
...some pyparsing tokens definitions...
INTEGER_EXPRESSION = EXPRESSION
RULE_NAME = SYMBOL
RULE_PROPERTY = OB + pp.Literal('salience') + INTEGER_EXPRESSION + CB
DECLARATION = OB + pp.Literal('declare') + pp.OneOrMore(RULE_PROPERTY) + CB
ACTION = EXPRESSION
CONNECTED_CONSTRAINT = pp.Forward()
TERM = CONSTANT | SINGLEFIELD_VARIABLE | MULTIFIELD_VARIABLE | pp.Literal(':') + FUNCTION_CALL | pp.Literal('=') + FUNCTION_CALL
SINGLE_CONSTRAINT = TERM | pp.Literal('~') + TERM
CONNECTED_CONSTRAINT << SINGLE_CONSTRAINT | SINGLE_CONSTRAINT + pp.Literal('&') + CONNECTED_CONSTRAINT
CONSTRAINT = pp.Literal('?') | pp.Literal('$?') | CONNECTED_CONSTRAINT
ORDERED_PATTERN_CE = OB + SYMBOL + pp.ZeroOrMore(CONSTRAINT) + CB
PATTERN_CE = ORDERED_PATTERN_CE
CONDITIONAL_ELEMENT = PATTERN_CE
DEFRULE_CONSTRUCT = OB + pp.Literal('defrule') + RULE_NAME + pp.Optional(COMMENT) + pp.Optional(DECLARATION) + pp.ZeroOrMore(CONDITIONAL_ELEMENT) + pp.Literal('=>') + pp.ZeroOrMore(ACTION) + CB
我已经省略了语法中某些部分的定义,因为它们太长了.
问题是解释器给了我这个奇怪的错误:
语法警告:无法将类型的元素与ParserElement组合
CONNECTED_CONSTRAINT<< SINGLE_CONSTRAINT | SINGLE_CONSTRAINT pp.Literal('&')CONNECTED_CONSTRAINT
我注意到,如果我写:
CONNECTED_CONSTRAINT << SINGLE_CONSTRAINT
代替:
CONNECTED_CONSTRAINT << SINGLE_CONSTRAINT | SINGLE_CONSTRAINT + pp.Literal('&') + CONNECTED_CONSTRAINT
它可以正常工作.
但是,即使我写这样的东西:
CONNECTED_CONSTRAINT << SINGLE_CONSTRAINT | pp.Literal('test')
这是行不通的.
因此,我想问题出在由“ |”给定的OR上符号,用pp.Forward()声明的令牌中.
请问你能帮帮我吗?
谢谢.
解决方法:
问题解决了.
这种问题在这里进行了解释:
http://pythonhosted.org/pyparsing/pyparsing.pyparsing.Forward-class.html
我必须写这样的表达式:
x << a | b
通过这种方式:
x << (a | b)
因为运算符“ |”优先级比运算符“<<”低. 还是要谢谢你!