python-3.x - 如何在匹配字符串后直到下一个匹配字符串将文本文件中的行分配给字典

标签 python-3.x dictionary

我正在尝试将居民放入字典中,并将居民作为住所的成员。这样,如果我搜索 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/

相关文章:

python - 通过列索引获取值,其中行是特定值

python - 根据数组中的唯一值拆分数组

Python 3.5 "ImportError: cannot import name ' 某个名字'

python - Pandas :从列 A 中提取 B 列不存在的数据

c++ - 我应该如何从 map<char, vector<char>> 生成所有可能的 map<char, char> 组合?

python - 如何将耗时添加到列表中

c++11 - STL map::insert 是否应该支持 move_iterators 的 move 语义?

python - 比较字典中列表中的任意数量的日期

python - dict.setdefault 将一个额外的(默认?)项目附加到值列表中

Python:用有序的字符串写一个空字典