字符串解析pyparsing中的复杂逻辑运算符

时间:2018-04-03 07:51:02

标签: python-3.x parsing query-string pyparsing

我正在尝试解析逻辑运算符,查询字符串见下文

code!=720 AND first_name=abc OR last_name=def AND status_code=OK

并将解析后的字符串作为二叉树。对于上面的表达式,预期的解析表达式应该看起来像

[[['code', '!=', '720'], 'AND', ['first_name', '=', 'abc']], 'OR', [['last_name', '=', 'def'], 'AND', ['status_code', '=', 'OK']]]

我试图做这个代码,但我没有得到所需的输出

operator = pp.Regex(">=|<=|!=|>|<|=").setName("operator")
number = pp.Regex(r'[+-]?\w+(:?\.\w*)?(:?[eE][+-]?\w+)?')
word = pp.Word(pp.alphas, pp.alphanums + "_-*(1234567890 ,)")
term = word | number
condition = pp.Group(term + operator + term)


expr = pp.operatorPrecedence(condition,
         [('NOT', 1, pp.opAssoc.RIGHT,),
          ('AND', 2, pp.opAssoc.LEFT,),
          ('OR', 2, pp.opAssoc.LEFT,)])

示例

query_string = 'code!=720 AND first_name=abc OR last_name=def AND status_code=OK'
print(expr.parseString(query_string)[0])

并输出错误

 [['code', '!=', '720'], 'AND', ['first_name', '=', 'abc OR last_name']]
你可以帮我写出正确的条件吗?

1 个答案:

答案 0 :(得分:2)

以上所有评论都包含在此代码中:

import pyparsing as pp

operator = pp.oneOf(">= <= != > < =").setName("operator")
number = pp.pyparsing_common.number()
# there is no space character in this pp.Word expression
word = pp.Word(pp.alphas, pp.alphanums + "_-*(1234567890,)")
term = word | number | pp.quotedString
condition = pp.Group(term + operator + term)


expr = pp.operatorPrecedence(condition,
         [('NOT', 1, pp.opAssoc.RIGHT,),
          ('AND', 2, pp.opAssoc.LEFT,),
          ('OR', 2, pp.opAssoc.LEFT,)])

query_string = 'code!=720 AND first_name=abc OR last_name=def AND status_code=OK'
print(expr.parseString(query_string, parseAll=True)[0])

给出了这个输出:

[[['code', '!=', 720], 'AND', ['first_name', '=', 'abc']], 'OR', [['last_name', '=', 'def'], 'AND', ['status_code', '=', 'OK']]]