Int*_*ure 0 python parsing list abstract-syntax-tree
所以我将文件解析为python列表,我遇到了这样的嵌套列表:
{ 1 4{ 2a 0.0 }{ 3 0.0 }{ 4c 0.0 }{ 5 0.0 } }
Run Code Online (Sandbox Code Playgroud)
我想把它解释为一个列表,但是嵌套了,所以我希望它成为python列表,如下所示:
[1,4,[2a,0.0],[3,0.0],[4c,0.0],[5,0.0]]
Run Code Online (Sandbox Code Playgroud)
我设法使用以下内容执行正确的字符串:
l = """{ 1 4{ 2 0.0 }{ 3 0.0 }{ 4 0.0 }{ 5 0.0 } }"""
l = l.replace("{\t",",[").replace("\t}","]").replace("{","[").replace("}","]").replace("\t",",")[1:]
Run Code Online (Sandbox Code Playgroud)
我也可以申请' l.strip("\t")以便它是一个列表,但不适用于嵌套,否则它将被展平,这是我不想要的.
我尝试过ast.literal_eval(l),但它在字符串上失败,例如2a
Pyparsing有一个内置的帮助器nestedExpr来帮助解析打开和关闭分隔符之间的嵌套列表:
>>> import pyparsing as pp
>>> nested_braces = pp.nestedExpr('{', '}')
>>> t = """{ 1 4{ 2a 0.0 }{ 3 0.0 }{ 4c 0.0 }{ 5 0.0 } }"""
>>> print(nested_braces.parseString(t).asList())
[['1', '4', ['2a', '0.0'], ['3', '0.0'], ['4c', '0.0'], ['5', '0.0']]]
Run Code Online (Sandbox Code Playgroud)