python-3.x - 从简单的文本文件中提取特定的文本部分
问题描述
当谈到 Python 时,我是一个新手,并且正在努力完成以下任务。希望有人可以提供帮助。
我有大量文件具有一些共同特征,尽管不是全部。在这些文件中是我需要提取的信息部分,但只有那些包含特定文本行的部分。这是其中一个文件中常见文本的片段:
房间 31
名称 "Bob"
没有电视插座 49
出口
房间 5
名称 "Ted"
service prov 10.1
出口 49-50,52
出口
房间 80
名称 "Alice"
出口 49-50,52
死出口 1-20
出口
房间 50
名称 "Tim "
outlet 49
exit
room 51
name "Sue"
service prov 10.2.0
outlet 49
exit
我要输出的是包含“service prov”的任何部分(包括同一行上的任何其他文本),因此以上面为例,我需要盯着“room 5”的文本(数量可能会有所不同)最多并包括“退出”,“51 号房间”也是如此 - 像这样:
房间 5
名称“Ted”
服务省 10.1
出口 49-50,52
出口
房间 51
名称“苏”
服务省 10.2.0
出口 49
出口
实现这一点的最简单方法是什么,记住该部分中的行数可以变化并出现在原始文本文件中的任何位置?
非常感谢所有建议(尤其是简单的建议)!谢谢!
解决方案
给定您问题中描述的形式的文本输入。这是我的做法:
def parse_input(in_data):
start_key = 'room'
end_key = 'exit'
trigger_key = 'service prov'
new_element = False
trigger_exists = False
out_data = ''
element_data = ''
for line in in_data:
if not new_element and start_key == line[:len(start_key)].lower():
new_element = True
element_data += f'{line}\n'
else:
element_data += f'{line}\n'
if trigger_key == line[:len(trigger_key)].lower():
trigger_exists = True
if end_key == line[:len(end_key)].lower():
if trigger_exists:
out_data += element_data
trigger_exists = False
new_element = False
element_data = ''
return out_data
执行
print(parse_input(lines))
产生:
room 5
name "Ted"
service prov 10.1
outlet 49-50,52
exit
room 51
name "Sue"
service prov 10.2.0
outlet 49
exit
推荐阅读
- python - 贪心算法 Python。获取所有序列
- r - 在 .r 中按月聚合(汇总)多个时间序列数据
- jquery - 根据布尔值禁用对行的编辑,但在所有行中都禁用了不应该的编辑
- pytest-bdd - Pytest-bdd 为场景大纲中定义的变量提供名称错误
- oracle - X11 从 macOS 10.15.4 到 OracleLinux7 失败
- asp.net-core-3.1 - 如果用户是 ASP.NET Core 3.1 MVC 中的管理员,则有条件地呈现 HTML 内容的最佳方式
- r - 如何将全局环境中的列表数据获取到列表中
- python - 加载到 Google Colab 后获取文件名
- java - maven“churchofjesuschrist.org”问题
- javascript - 使用 .push 更新对象以添加新元素