繁体   English   中英

在两行字符串之间的文本文件中提取行

[英]extracting lines in a text file between two lines of strings

我有以下示例文本文件(它的格式如下所示)。 我想在“生成配置....”和“`show accounting log all`”这两行之间提取所有内容,这是我感兴趣的开始和结束。

一些台词
一些更多的线
生成配置....
感兴趣的配置
感兴趣的配置
感兴趣的配置
`show accounting log all
一些台词
一些更多的线

我写了下面的代码,但是在找到`show accounting log all`后,它不会停止将行附加到文本文件中。

    config_found = False
    with open(filename, 'rb') as f:
        textfile_temp = f.readlines()

    for line in textfile_temp:
        if re.match("Generating configuration....", line):
            config_found = True
        if re.match("`show accounting log all`", line):
            config_found = False
        if config_found:
            i = line.rstrip()
            textfile.append(i)

我的陈述怎么办?

您必须在比较中使用if引用而不是单引号,并且可以使用if和elif在字符串之间进行提取。 我修改如下,它的工作原理:

with open('file.txt', 'rb') as f:
    textfile_temp = f.readlines()
    config_found = False
    textfile = []
    for line in textfile_temp:
        if re.match("`show accounting log all`", line):
            config_found = False
        elif config_found:
            i = line.rstrip()
            textfile.append(i)
        elif re.match("Generating configuration....", line):
            config_found = True
    print textfile

输出:

  ['interested config', 'interested config', 'interested config']

相反,您可以使用拆分如下:

 with open('file.txt', 'rb') as f:
     textfile_temp = f.read()
     print textfile_temp.split('Generating configuration....')[1].split("`show accounting log all`")[0]

输出:

interested config 
interested config 
interested config 

config_found似乎没有在循环之外的范围。

在循环之前放置config_found = False ,它应该可以正常工作。

暂无
暂无

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

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