我正在尝试将居民放入字典中,并将居民作为住所的成员。这样,如果我搜索 Bill,它将返回 There is a Bill located at Res-Condo-2 and Res-Condo-1。我正在读取的文本文件如下所示:
************
Ohio
************
Res-House-1
Mickey
Minnie
Goofy
Res-Apt-1
Fred
Barnie
Wilma
Res-Condo-2
Bill
************
Ohio
************
Res-House-2
Stan
Francine
Haley
Stve
Res-Condo-1
Bill
我能够读取文件并创建居住地列表,但我无法获取其他元素。我还注意到列表末尾包含新行。
list = []
with open('Residencies') as f:
for line in o:
if "Res" in line:
list.append(line)
print(list)
打印语句输出
['Res-House-1\n', 'Res-Apt-1\n', 'Res-Codo-2\n', 'Res-House-2\n', 'Res-Condo-1\n']
如何获取字典中的每个住所,以便我可以搜索哪个居民属于哪个住所?
最佳答案
按居住地对居民进行分组:
from collections import defaultdict
with open('Residencies.txt') as f:
residencies = defaultdict(list)
for line in f:
line = line.strip()
if not line: continue # skip empty line
if line.startswith('**'): # skip *** state block
next(f)
next(f)
continue
if line.startswith('Res'):
k = line
continue
residencies[k].append(line)
print(dict(residencies))
输出:
{'Res-Apt-1': ['Fred', 'Barnie', 'Wilma'],
'Res-Condo-1': ['Bill'],
'Res-Condo-2': ['Bill'],
'Res-House-1': ['Mickey', 'Minnie', 'Goofy'],
'Res-House-2': ['Stan', 'Francine', 'Haley', 'Stve']}
关于python-3.x - 如何在匹配字符串后直到下一个匹配字符串将文本文件中的行分配给字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596248/