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

1 投票
2 回答
4744 浏览
提问于 2025-04-17 23:55

我有一个示例文本文件(格式如下)。我想提取“Generating configuration....”和“`show accounting log all`”这两行之间的所有内容,这就是我感兴趣的部分。

一些行
更多的行
Generating configuration....
感兴趣的配置
感兴趣的配置
感兴趣的配置
`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

config_found 这个变量在循环外面是无法使用的。

在循环之前加上 config_found = False,这样就可以正常工作了。

3

在比较的时候,你需要用反引号(`)而不是单引号(')。而且你可以用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']

另外,你也可以使用split方法,像下面这样:

 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 

撰写回答