我正在读取一个基本上包含嵌套扁平字典的输入文件,如下所示:
&HEADER
header line 0
header line 1
&End_HEADER
some other line 1
some other line 2
#XXX0
line 0
line 1
line 2
#AAA0
line 0
line 1
line 2
...
#AAA1
line 0
line 1
...
#BBB0
line 0
line 1
...
#BBB1
line 0
...
#XXX1
line 0
...
#AAA0
line 0
...
#AAA1
...
#BBB0
...
您可以注意到有三个部分,每个部分由几行组成:标题、一些单独的行和一个扁平的嵌套字典。我对后者最感兴趣,但理想情况下,我希望对其进行解析,以便得到以下结果:
{
'HEADER': ['header line 0', 'header line 1'],
'other lines': ['some other line 1', 'some other line 2'],
'XXX0': {
'HEADER': ['line 0', 'line 1', 'line 2'],
'AAA0': ['line 0', 'line 1', 'line 2', '...'],
'AAA1': ['line 0', 'line 1', '...'],
'BBB0': ['line 0', 'line 1', '...'],
'BBB1': ['line 0', '...']
},
'XXX1': {
'HEADER': ['line 0', '...'],
'AAA0': ['line 0', '...'],
'AAA1': ['...'],
'BBB0': ['...']
}
}
我目前正在遍历每一行,并使用if语句将每一行附加到嵌套字典中。它是有效的,但它是丑陋的,我怀疑这可以做得更优雅,也许使用递归,defaultdict或正则表达式。我的脑袋绕不过去。你能帮我找到更好的方法吗?非常感谢
这就是我的想法
Pythonic
是相当主观的,但这种方法可以使它容易遵循?这不包括顶部的头部分,但也可以很容易地解析。一旦你解析了它,你就可以把字典合并在一起输出:
相关问题 更多 >
编程相关推荐