从无法使用 ast.literal_eval 解析的字符串解析嵌套列表 [英] Parse nested list from string that cannot be parsed with ast.literal_eval
问题描述
我将文件解析为 Python 列表,但遇到了这样的嵌套列表:
{ 1 4{ 2a 0.0 }{ 3 0.0 }{ 4c 0.0 }{ 5 0.0 } }
我想把它解释为一个列表,但嵌套了,所以我想成为这样的结果Python列表:
[1,4,[2a,0.0],[3,0.0],[4c,0.0],[5,0.0]]
我设法使用以下内容执行正确的字符串:
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:]
我也可以应用 l.strip("\t")
使它是一个列表,但不是嵌套的,否则它会被展平,这是我不想要的.
我尝试使用 ast.literal_eval(l)
,但它在字符串上失败,例如2a
Pyparsing 有一个内置的帮助器 nestedExpr
来帮助解析开始和结束分隔符之间的嵌套列表:
I parse a file to a Python list and I encountered a nested list like this:
{ 1 4{ 2a 0.0 }{ 3 0.0 }{ 4c 0.0 }{ 5 0.0 } }
I want to interpret it as a list, yet nested, so I want to be the resulting Python list as follows:
[1,4,[2a,0.0],[3,0.0],[4c,0.0],[5,0.0]]
I manage to do a correct string of this with a following:
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:]
I can also apply l.strip("\t")
so that it is a list, but not for a nested, otherwise it will be flattened, which I do not want.
I tried with ast.literal_eval(l)
, but it fails on strings e.g. 2a
Pyparsing has a built-in helper nestedExpr
to help parse nested lists between opening and closing delimiters:
>>> 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']]]
这篇关于从无法使用 ast.literal_eval 解析的字符串解析嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!