Python parsing bracketed blocks

后端 未结 9 1947
独厮守ぢ
独厮守ぢ 2020-11-27 04:44

What would be the best way in Python to parse out chunks of text contained in matching brackets?

\"{ { a } { b } { { { c } } } }\"

should i

9条回答
  •  失恋的感觉
    2020-11-27 05:15

    Using Grako (grammar compiler):

    #!/usr/bin/env python
    import json
    import grako # $ pip install grako
    
    grammar_ebnf = """
        bracketed = '{' @:( { bracketed }+ | any ) '}' ;
        any = /[^{}]+?/ ;
    """
    model = grako.genmodel("Bracketed", grammar_ebnf)
    ast = model.parse("{ { a } { b } { { { c } } } }", "bracketed")
    print(json.dumps(ast, indent=4))
    

    Output

    [
        "a", 
        "b", 
        [
            [
                "c"
            ]
        ]
    ]
    

提交回复
热议问题