簡體   English   中英

我應該如何定義一個在 LARK 中同時支持 NOT 和 AND NOT 的 NOT 運算符

[英]How should I define a NOT operator which supports both NOT and AND NOT in LARK

這是我當前代碼的樣子,它只支持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

我認為這應該做你問的:

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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM