19

我正在尝试解析如下所示的复杂逻辑表达式;

x > 7 AND x < 8 OR x = 4

并将解析后的字符串作为二叉树获取。对于上述表达式,预期的解析表达式应如下所示

[['x', '>', 7], 'AND', [['x', '<', 8], 'OR', ['x', '=', 4]]]

“OR”逻辑运算符的优先级高于“AND”运算符。括号可以覆盖默认优先级。更一般地说,解析后的表达式应该是这样的;

<left_expr> <logical_operator> <right_expr>

另一个例子是

input_string = x > 7 AND x < 8 AND x = 4
parsed_expr  = [[['x', '>', 7], 'AND', ['x', ',', 8]], 'AND', ['x', '=', 4]]

到目前为止,我想出了这个简单的解决方案,遗憾的是它无法以二叉树的方式生成解析表达式。operatorPrecedence 在这里似乎没有帮助我,因为与前面的示例中连续存在相同的逻辑运算符。

import pyparsing as pp
complex_expr = pp.Forward()
operator = pp.Regex(">=|<=|!=|>|<|=").setName("operator")
logical = (pp.Keyword("AND") | pp.Keyword("OR")).setName("logical")
vars = pp.Word(pp.alphas, pp.alphanums + "_") | pp.Regex(r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")
condition = (vars + operator + vars)
clause = pp.Group(condition ^ (pp.Suppress("(") + complex_expr + pp.Suppress(")") ))

expr = pp.operatorPrecedence(clause,[
                            ("OR", 2, pp.opAssoc.LEFT, ),
                            ("AND", 2, pp.opAssoc.LEFT, ),])

complex_expr << expr
print complex_expr.parseString("x > 7 AND x < 8 AND x = 4")

非常感谢任何建议或指导。

BNF对于表达式(不带括号)可以是

<expr>       -> <expr> | <expr> <logical> <expr>
<expr>       -> <opnd> <relational> <opnd>
<opnd>       -> <variable> | <numeric>
<relational> -> <'>'> | <'='> | <'>='> | <'<='> | <'!='>
4

2 回答 2

16

注意:operatorPrecedence不推荐使用 pyparsing 的方法,取而代之的是方法名称infixNotation

尝试改变:

expr = pp.operatorPrecedence(clause,[ 
                            ("OR", 2, pp.opAssoc.LEFT, ), 
                            ("AND", 2, pp.opAssoc.LEFT, ),]) 

至:

expr = pp.operatorPrecedence(condition,[ 
                            ("OR", 2, pp.opAssoc.LEFT, ), 
                            ("AND", 2, pp.opAssoc.LEFT, ),]) 

operatorPrecedence 的第一个参数是要与运算符一起使用的原始操作数 - 无需在括号中包含您的 complexExpr - operatorPrecedence 将为您执行此操作。由于您的操作数实际上是另一个更深入的比较,您可能会考虑更改:

condition = (expr + operator + expr)

至:

condition = pp.Group(expr + operator + expr)

使 operatorPrecedence 的输出更容易处理。通过这些更改,解析x > 7 AND x < 8 OR x = 4给出:

[[['x', '>', '7'], 'AND', [['x', '<', '8'], 'OR', ['x', '=', '4']]]]

它识别 OR 的更高优先级并首先对其进行分组。(您确定要这种 AND 和 OR 优先顺序吗?我认为传统的顺序是相反的,如本维基百科条目所示。)

我想你也在问为什么 pyparsing 和 operatorPrecedence 不返回嵌套二进制对的结果,也就是说,你期望解析“A and B and C”会返回:

[['A', 'and', 'B'] 'and', 'C']

但你得到的是:

['A', 'and', 'B', 'and', 'C']

这是因为 operatorPrecedence 使用重复而不是递归来解析相同优先级的重复操作。请参阅与您的问题非常相似的这个问题,其答案包括将重复解析树转换为更传统的二叉解析树的解析操作。您还可以在 pyparsing wiki 页面上找到使用 operatorPrecedence 实现的示例布尔表达式解析器。

编辑:为了澄清,我建议您将解析器减少到:

import pyparsing as pp

operator = pp.Regex(">=|<=|!=|>|<|=").setName("operator")
number = pp.Regex(r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")
identifier = pp.Word(pp.alphas, pp.alphanums + "_")
comparison_term = identifier | number 
condition = pp.Group(comparison_term + operator + comparison_term)

expr = pp.operatorPrecedence(condition,[
                            ("AND", 2, pp.opAssoc.LEFT, ),
                            ("OR", 2, pp.opAssoc.LEFT, ),
                            ])

print expr.parseString("x > 7 AND x < 8 OR x = 4")

如果您还想添加对 NOT 的支持,则如下所示:

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

在某些时候,您可能希望comparison_term使用更完整的算术表达式来扩展 的定义,并使用它自己的定义进行operatorPrecedence定义。我建议这样做,而不是创建一个怪物opPrec定义,因为您已经提到了opPrec. 如果您仍然遇到性能问题,请查看ParserElement.enablePackrat.

于 2012-06-21T08:59:44.663 回答
7

让我建议这种解析方法,它直接来自 Peter Norvig 在 udacity 的计算机程序设计课程(并根据您的需要进行了调整)。

from functools import update_wrapper
from string import split
import re

def grammar(description, whitespace=r'\s*'):
    """Convert a description to a grammar.  Each line is a rule for a
    non-terminal symbol; it looks like this:
        Symbol =>  A1 A2 ... | B1 B2 ... | C1 C2 ...
    where the right-hand side is one or more alternatives, separated by
    the '|' sign.  Each alternative is a sequence of atoms, separated by
    spaces.  An atom is either a symbol on some left-hand side, or it is
    a regular expression that will be passed to re.match to match a token.

    Notation for *, +, or ? not allowed in a rule alternative (but ok
    within a token). Use '\' to continue long lines.  You must include spaces
    or tabs around '=>' and '|'. That's within the grammar description itself.
    The grammar that gets defined allows whitespace between tokens by default;
    specify '' as the second argument to grammar() to disallow this (or supply
    any regular expression to describe allowable whitespace between tokens)."""
    G = {' ': whitespace}
    description = description.replace('\t', ' ') # no tabs!
    for line in split(description, '\n'):
        lhs, rhs = split(line, ' => ', 1)
        alternatives = split(rhs, ' | ')
        G[lhs] = tuple(map(split, alternatives))
    return G

def decorator(d):
    def _d(fn):
        return update_wrapper(d(fn), fn)
    update_wrapper(_d, d)
    return _d

@decorator
def memo(f):
    cache = {}
    def _f(*args):
        try:
            return cache[args]
        except KeyError:
            cache[args] = result = f(*args)
            return result
        except TypeError:
            # some element of args can't be a dict key
            return f(args)
    return _f

def parse(start_symbol, text, grammar):
    """Example call: parse('Exp', '3*x + b', G).
    Returns a (tree, remainder) pair. If remainder is '', it parsed the whole
    string. Failure iff remainder is None. This is a deterministic PEG parser,
    so rule order (left-to-right) matters. Do 'E => T op E | T', putting the
    longest parse first; don't do 'E => T | T op E'
    Also, no left recursion allowed: don't do 'E => E op T'"""

    tokenizer = grammar[' '] + '(%s)'

    def parse_sequence(sequence, text):
        result = []
        for atom in sequence:
            tree, text = parse_atom(atom, text)
            if text is None: return Fail
            result.append(tree)
        return result, text

    @memo
    def parse_atom(atom, text):
        if atom in grammar:  # Non-Terminal: tuple of alternatives
            for alternative in grammar[atom]:
                tree, rem = parse_sequence(alternative, text)
                if rem is not None: return [atom]+tree, rem  
            return Fail
        else:  # Terminal: match characters against start of text
            m = re.match(tokenizer % atom, text)
            return Fail if (not m) else (m.group(1), text[m.end():])

    # Body of parse:
    return parse_atom(start_symbol, text)

Fail = (None, None)

MyLang = grammar("""expression => block logicalop expression | block
block => variable operator number
variable => [a-z]+
operator => <=|>=|>|<|=
number => [-+]?[0-9]+
logicalop => AND|OR""", whitespace='\s*')

def parse_it(text):
    return parse('expression', text, MyLang)

print parse_it("x > 7 AND x < 8 AND x = 4")

输出:

(['expression', ['block', ['variable', 'x'], ['operator', '>'], ['number', '7']], ['logicalop', 'AND'], ['expression', ['block', ['variable', 'x'], ['operator', '<'], ['number', '8']], ['logicalop', 'AND'], ['expression', ['block', ['variable', 'x'], ['operator', '='], ['number', '4']]]]], '')
于 2012-06-21T09:11:45.513 回答