将行收集到列表中,同时将该列表存储在字典中:
d = {}
values = None
with open(filename) as inputfile:
for line in inputfile:
line = line.strip()
if line.startswith('Clutch'):
values = d[line] = []
else:
values.append(line)
这将给你带来:
{'Clutch001': ['Albino X Pastel', 'Bumble Bee X Albino Lesser']
'Clutch002': ['Bee X Fire Bee', 'Albino Cinnamon X Albino', 'Mojave X Bumble Bee']
'Clutch003': ['Black Pastel X Banana Ghost Lesser']}
在加载文件后,将所有这些列表转化为单个字符串非常容易:
d = {key: ', '.join(value) for key, value in d.items()}
您也可以在读取文件时进行连接; 我会使用生成器函数以组的形式处理文件:
def per_clutch(inputfile):
clutch = None
lines = []
for line in inputfile:
line = line.strip()
if line.startswith('Clutch'):
if lines:
yield clutch, lines
clutch, lines = line, []
else:
lines.append(line)
if clutch and lines:
yield clutch, lines
然后将所有组都放入一个字典中:
with open(filename) as inputfile:
d = {clutch: ', '.join(lines) for clutch, lines in per_clutch(inputfile)}
演示后者的例子:
>>> def per_clutch(inputfile):
... clutch = None
... lines = []
... for line in inputfile:
... line = line.strip()
... if line.startswith('Clutch'):
... if lines:
... yield clutch, lines
... clutch, lines = line, []
... else:
... lines.append(line)
... if clutch and lines:
... yield clutch, lines
...
>>> sample = '''\
... Clutch001
... Albino X Pastel
... Bumble Bee X Albino Lesser
... Clutch002
... Bee X Fire Bee
... Albino Cinnamon X Albino
... Mojave X Bumble Bee
... Clutch003
... Black Pastel X Banana Ghost Lesser
... '''.splitlines(True)
>>> {clutch: ', '.join(lines) for clutch, lines in per_clutch(sample)}
{'Clutch001': 'Albino X Pastel, Bumble Bee X Albino Lesser', 'Clutch002': 'Bee X Fire Bee, Albino Cinnamon X Albino, Mojave X Bumble Bee', 'Clutch003': 'Black Pastel X Banana Ghost Lesser'}
>>> from pprint import pprint
>>> pprint(_)
{'Clutch001': 'Albino X Pastel, Bumble Bee X Albino Lesser',
'Clutch002': 'Bee X Fire Bee, Albino Cinnamon X Albino, Mojave X Bumble Bee',
'Clutch003': 'Black Pastel X Banana Ghost Lesser'}
.split('Clutch')
。 - Stuart