首页 > 解决方案 > 如何在匹配字符串后将文本文件中的行分配给字典,直到下一个匹配字符串

问题描述

我正在尝试将居民的字典与居民作为住所的成员。这样,如果我搜索 Bill,它将返回 There is a Bill 位于 Res-Condo-2 和 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']

如何在字典中获取每个住所,以便我可以搜索哪个住户属于哪个住所?

标签: python-3.xdictionary

解决方案


让我们先忽略不相关的行(eq 空行***等)

if line.startswith('*') or line.startswith(' '):
    continue
line = line.strip()

if not line:
    continue

现在只需跟踪您看到的最后一个住所。该住所后面的所有名字都住在那里。将此信息放入字典中,键为人名,值为住所列表。

from collections import defaultdict

home = defaultdict(list)
last = None

with open('Residencies') as f:
    for line in f:
        if line.startswith('*') or line.startswith(' '):
            continue
        line = line.strip()

        if not line:
            continue

        if 'Res' in line:
            last = line
        else:
            home[line].append(last)

print(home['Bill'])

输出:['Res-Condo-2', 'Res-Condo-1']

list此外,作为变量的名称也不是一个好主意。


推荐阅读