首页 > 解决方案 > 从简单的文本文件中提取特定的文本部分

问题描述

当谈到 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
出口

实现这一点的最简单方法是什么,记住该部分中的行数可以变化并出现在原始文本文件中的任何位置?

非常感谢所有建议(尤其是简单的建议)!谢谢!

标签: python-3.xtextextract

解决方案


给定您问题中描述的形式的文本输入。这是我的做法:

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

 
    

推荐阅读