0

这是我当前代码的样子,它只支持a AND NOT b. 有没有办法让它也返回同一棵树a NOT b?任何建议将不胜感激。

from lark import Lark


grammar = r'''
    start: or_test

    ?or_test: and_test ("OR" and_test)*
    ?and_test: not_test ("AND" not_test)*
    ?not_test: "NOT" not_test -> not
             | atom
    
    atom: WORD -> term
         | "(" or_test ")"

    WORD: /[a-zA-Z0-9]+/
    
    %import common.WS_INLINE
    %ignore WS_INLINE
'''

parser = Lark(grammar)

s = 'NOT a AND b AND NOT c'
tree = parser.parse(s)
print(tree.pretty())

输出

start
  and_test
    not
      term  a
    term    b
    not
      term  c
4

1 回答 1

0

我认为这应该做你问的:

from lark import Lark

grammar = r'''
    start: or_test

    ?or_test: and_test ("OR" and_test)*
    ?and_test: not_test ("AND" not_test | and_not)*
    and_not: "NOT" not_test -> not
    ?not_test: "NOT" not_test -> not
            | atom

    atom: WORD -> term
        | "(" or_test ")"

    WORD: /[a-zA-Z0-9]+/

    %import common.WS_INLINE
    %ignore WS_INLINE
'''

parser = Lark(grammar)

s = 'NOT a AND b AND NOT c NOT d'
tree = parser.parse(s)
print(tree.pretty())
于 2020-11-28T10:06:39.930 回答