python-3.x - 如何在匹配字符串后将文本文件中的行分配给字典,直到下一个匹配字符串
问题描述
我正在尝试将居民的字典与居民作为住所的成员。这样,如果我搜索 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']
如何在字典中获取每个住所,以便我可以搜索哪个住户属于哪个住所?
解决方案
让我们先忽略不相关的行(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
此外,作为变量的名称也不是一个好主意。
推荐阅读
- postgresql - Postgres:如何在 psql 查询中的字符串中插入双引号?
- r - 关于一个词的意见
- javascript - convert list of slugs into json in Javascript
- reactjs - Typescript + React useReducer 钩子错误:数据对象不可分配给“从不”类型的参数
- python - bash 脚本返回状态 -13
- c++ - 如何在使用递归函数时处理堆栈溢出
- sql - 比较两个日期并计算日期差
- java - Windows系统的Java内存映射文件
- java - 如何设置列的Jtable名称
- sql - OracleSQL 比较基于整数列的日期