我正在尝试寻找文本块,并将一些行放入字典数组中。所以我找到的每个文本块都有一本字典。例如以下文本:
some
other
text
address-object object1
name "name1"
uuid 4ac9cf52-02b5-eecf-0100-18c24100da5e
zone zone1
host ip1
exit
address-object object2
name "name2"
uuid a5c02150-a47e-748d-0100-18c24100da5e
zone zone2
host ip2
exit
some
more text
例如,我想在每个块的数组中存储 ip 和区域,这样我最终会得到
[[host:ip1,zone:zone1],[host:ip2,zone:zone2]]
。
我尝试循环遍历文本文件,但无法正确循环块。我想我必须使用某种形式的迭代,但我不确定。我最终得到一个数组,其中包含从第一个地址对象行到某个关键字的所有项目。我需要为每个地址对象一个循环,并在遇到空行时得到下一个。
importantKeys = {'host', 'zone'}
with open('path/to/file') as infile:
answer = [{}]
for line in infile:
k,_,v = line.strip().partition(' ')
if k in importantKeys:
answer[-1][k] = v
if len(answer[-1]) == len(importantKeys):
answer.append({})
结果:
In [28]: answer
Out[28]: [{'zone': 'zone1', 'host': 'ip1'}, {'zone': 'zone2', 'host': 'ip2'}, {}]
In [29]: answer = [d for d in answer if d]
In [30]: answer
Out[30]: [{'zone': 'zone1', 'host': 'ip1'}, {'zone': 'zone2', 'host': 'ip2'}]