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

时间:2014-03-26 03:50:36

标签: python

我有以下示例文本文件(格式如下所示)。我想在行之间提取所有内容"生成配置...."和"`显示会计记录全部`",这是我感兴趣的开始和结束。

有些线路 更多行 生成配置.... 感兴趣的配置
感兴趣的配置
感兴趣的配置
`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)

我的陈述是怎么回事?

2 个答案:

答案 0 :(得分:2)

而不是单引号,你必须在比较中使用反引号,你可以使用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 

答案 1 :(得分:0)

config_found似乎没有之外的范围。

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

相关问题