匹配后,Python提取文本4行 [英] Python extract text 4 lines after match

查看:26
本文介绍了匹配后,Python提取文本4行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个文本文件,我需要提取一行文本,在特定标题之后4行。

即:
标题
第1行
第2行
第3行
要提取的行

我花了几个小时寻找一种简单的方法来做这件事,但我对Python的了解太有限,无法将我找到的任何东西应用到这个特定的案例中。谢谢!

推荐答案

找到标题,然后只取下四行,最后一行就是您想要的。

from itertools import islice

with open("words.txt") as f:
    for line in f:
        if line.rstrip() == "Heading":
            print(list(islice(f, 4))[-1])
            break
line to be extracted

或使用行缓存获取Heading行后4行:

from linecache import getline
with open("words.txt") as f:
    for ind, line in enumerate(f,1):
        if line.rstrip() == "Heading":
            print(getline(f.name, ind + 4))
            break
line to be extracted

如果您有多行,请不要中断。

from linecache import getline
with open("words.txt") as f:
    for ind, line in enumerate(f,1):
        if line.rstrip() == "Heading":
            print(getline(f.name, ind + 4))

line to be extracted

other line to be extracted

这篇关于匹配后,Python提取文本4行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆