尝试pyparsing。这是一个支持相等、布尔运算和嵌套括号的语法解析器:
from pyparsing import *
expr = Forward()
factor = Forward()
term = Forward()
iand = Literal("AND").suppress()
ior = Literal("OR").suppress()
ieq = Literal("=").suppress()
lpar = Literal("(").suppress()
rpar = Literal(")").suppress()
ident = Word(alphas)
atom = ident | lpar + expr + rpar
factor << Group(atom + ZeroOrMore(ieq + atom))("equal")
term << Group(factor + ZeroOrMore(iand + term))("and")
expr << Group(term + ZeroOrMore(ior + expr))("or")
您可以将其应用于您的公式以获得类似树的结构,您可以稍后对其进行评估,例如:
formula = "(assignee=cdecker OR due=tomorrow) AND status=open"
tree = expr.parseString(formula, parseAll=True)
print tree.asXML()