首页 > 解决方案 > 在python中提取文件的两行之间的一行

问题描述

我有如图所示的文本文件。

在此处输入图像描述

当标题出现在两条虚线之间时,我想提取标题(虚线位置不固定)。但是在迭代时无法检查上一行和下一行。

有人可以提出一些想法我该怎么做?

标签: python-3.x

解决方案


如果您在迭代时无法检查上一行和下一行,您可以跟踪何时看到虚线。当看到第一条虚线时,您开始追加文本,当遇到下一条虚线时,您停止追加,例如

headings = []
start = 0
with open('/home/usr3/test1.txt') as f:
    for ln in f:
        # append to heading list
        if start == 1:
            # when the second dashed line is seen, stop appending
            if ln.startswith('---'):
                start = 0
                continue
            headings.append(ln.rstrip())
        # first dashed line, indicate to start appending
        if ln.startswith('---'):
            start = 1

对于文本:

------------
h1
-------------
qww
qwe
qw
eqwe
-------------
h2
-------------
qwqw
ee
e
e
e
------------- 
h3
-------------

输出是:

['h1', 'h2', 'h3']

推荐阅读