Python3-云雀:使用可选终端处理规则的便捷方式?

dgsult0t  于 2023-03-20  发布在  Python
关注(0)|答案(1)|浏览(135)

在一个语法规则中,比如下面这个:

top_rule: header? body footer?
?header: "DAY" DAY
       | "SECT" SECT  
?body: BODY
?footer: "ENDING" 
       | "TERMINATING"  

DAY: /\[^s]+/
SECT: /\d+/
BODY: /\[^s]+/

变压器法最方便的方法是什么?

  • 我应该选择@v_args(inline=True)吗?在这种情况下,我必须处理*args的长度,并根据它们来处理if-else情况。
  • 我是否应该使用@v_args(tree=True)?通过遍历AST子节点来检查AST是否包含规则?

在python3中:

#!/usr/bin/python3

from lark import Lark, Transformer, v_args

GRAMMAR = r"""

 top_rule: header? body footer?
 ?header: "DAY" DAY
        | "SECT" SECT  
 ?body: BODY
 ?footer: "ENDING" DAY
        | "TERMINATING" DAY  

 DAY: /\[^s]+/
 SECT: /\d+/
 BODY: /\[^s]+/
"""

def MyTransformer(Transformer)

    @v_args(inline=True)
    def top_rule(self, *args):
        if len(args) == 3:
             # all optionals are used of the rule...
        elif len(args) == 1: 
             # no optionals (header/footer) used...
        else: 
             # can be args(header, body) or args(body, footer)...

什么是合适的处理方法?我错过了什么吗?或者这是应该走的路吗?据我所知,我不能有多个基于参数数量的top_rule方法。

tag5nh1u

tag5nh1u1#

使用inline=True[TERMINAL]代替TERMINAL?,然后lark在None中填充缺少的端子:

from lark import Lark, Transformer, v_args

GRAMMAR = r"""

 top_rule: [header] body [footer]
 ?header: "DAY" DAY
        | "SECT" SECT  
 ?body: BODY
 ?footer: "ENDING" DAY
        | "TERMINATING" DAY  

 DAY: /\[^s]+/
 SECT: /\d+/
 BODY: /\[^s]+/
"""

def MyTransformer(Transformer)
    @v_args(inline=True)
    def top_rule(self, header: Token | None, body: Token, footer: Token | None):
        if header is not None:
             # header is being used
        if footer is not None: 
             # footer is being used
        # body will always be there.

相关问题