我尝试使用 pyparsing 来解析诸如这些的逻辑表达式
x
FALSE
NOT x
(x + y <= 5) AND (y >= 10) OR NOT (z < 100 OR w)
(A=True OR NOT (G < 8) => S = J) => ((P = A) AND not (P = 1) AND (B = O)) => (S = T)
((P = T) AND NOT (K =J) AND (B = F)) => (S = O) AND
((P = T) OR (k and b => (8 + z <= 10)) AND NOT (a + 9 <= F)) => (7 = a + z)
我在下面编写的代码似乎可以正常工作——但速度很慢(例如上面的最后一个示例需要几秒钟)。我是否以某种低效的方式构建语法?可能应该使用递归而不是 operatorPrecedence ?有没有办法加快速度?
identifier = Group(Word(alphas, alphanums + "_") + Optional("'"))
num = Regex(r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")
operator = Regex(">=|<=|!=|>|<|=")
operand = identifier | num
aexpr = operatorPrecedence(operand,
[('*',2,opAssoc.LEFT,),
('+',2,opAssoc.LEFT,),
(operator,2,opAssoc.LEFT,)
])
op_prec = [(CaselessLiteral('not'),1,opAssoc.RIGHT,),
(CaselessLiteral('and'),2,opAssoc.LEFT ,),
(CaselessLiteral('or'), 2,opAssoc.LEFT ,),
('=>', 2,opAssoc.LEFT ,),
]
sentence = operatorPrecedence(aexpr,op_prec)
return sentence