繁体   English   中英

Python 3.x打印特定标题后的行数

[英]Python 3.x print number of lines after a specific header

我有一个似乎无法解决的问题; 道歉,如果这是重复但从来没有真正的答案。 我正在从配置文件中提取特定信息,该文件以文本块的形式显示信息,我只需要打印特定的块,而不需要标题。 所以例如(使用下面的文本格式)我只想捕获Header2下面的信息,但不想捕获标题3之外的任何信息:

#   output could containmultiple headers, and lines, or no lines per header this is an example of what could be present but it is not absolute. 

header1
-------
line1
line2
line3 # can be muiplies availables or known

header2
-------
line1
line2
line3 # can be muiplies availables or known

header3
-------

header4
-------
line1
line2
line3 # can be multiple linnes or none not known 

这是我开始使用的代码,但卡在第二个循环布尔或逻辑上,只打印该标题块的行:

Raw_file = "scrap.txt"
scrape = open(Raw_file,"r") 


for fooline in scrape:

        if "Header" in fooline:
                #print(fooline) # prints all lines
                    #print lines under header 2 and stop before header 3



scrape.close()

使用标题行的检测来打开/关闭控制打印的布尔值:

RAW_FILE = "scrap.txt"

DESIRED = 'header2'

with open(RAW_FILE) as scrape:

    printing = False

    for line in scrape:

        if line.startswith(DESIRED):
            printing = True
        elif line.startswith('header'):
            printing = False
        elif line.startswith('-------'):
            continue
        elif printing:
            print(line, end='')

OUTPUT

> python3 test.py
line1
line2
line3 # can be muiplies availables or known

>

根据需要调整。

您可以考虑使用正则表达式将其分解为块。

如果文件具有可管理的大小,请立即全部阅读并使用正则表达式:

(^header\d+[\s\S]+?(?=^header|\Z))

把它分成块。 演示

然后你的Python代码看起来像这样(在标题之间获取任何文本):

import re

with open(fn) as f:
    txt=f.read()

for m in re.finditer(r'(^header\d+[\s\S]+?(?=^header|\Z))', txt, re.M):
    print(m.group(1))

如果文件大于您想要在一个gulp中读取的文件,则可以将mmap与正则表达式一起使用,并以相当大的块读取文件。

如果您只查找单个标题,则更容易:

m=re.search(r'(^header2[\s\S]+?(?=^header|\Z))', txt, re.M)
if m:
    print(m.group(1))

正则表达式的演示

您可以根据匹配的header2header3内容设置启动和停止收集的标志。

使用example.txt包含提供的完整示例数据:

f = "example.txt"
scrape = open(f,"r") 

collect = 0
wanted = []

for fooline in scrape:
    if "header2" in fooline:
        collect = 1
    if "header3" in fooline:
        collect = 2

    if collect == 1:
        wanted.append(fooline)
    elif collect == 2:
        break

scrape.close()

wanted输出:

['header2\n',
 '-------\n',
 'line1\n',
 'line2\n',
 'line3 # can be muiplies availables or known\n',
 '\n']

最初,将flag设置为False 检查该行是否以header2 如果为True ,则设置flag 如果该行以header3 ,则将flag设置为False

如果设置了flag则打印行。

Raw_file = "scrap.txt"
scrape = open(Raw_file,"r") 
flag = False

for fooline in scrape:
    if fooline.find("header3") == 0: flag = False # or break
    if flag:
        print(fooline)
    if fooline.find("header2") == 0: flag = True
scrape.close()

输出:

-------

line1

line2

line3 # can be muiplies availables or known

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM