首页 > 解决方案 > 如何在单个 gzip 文件中搜索多个字符串?

问题描述

我正在尝试打开一个 zip 文件并搜索特定的字符串。在这里,如果'result =one'那么我应该在同一个文件中搜索另一个名为'next'的特定字符串,但在不同的行中并打印包含'next'的行。

例子:

next line
result = one
asdfgh
...
waiting for next line
please wait to print the next line

所以首先它应该搜索'result = one',然后它应该在文件中搜索'next'。
预期输出:

next line
waiting for next line
please wait to print the next line

我正在尝试的工作

     with gzip.open ('result.gz', 'rt') as i:
         for line in i:
             if 'result = one' in line:
                 continue
                 if 'next' in line:
                     print (line)

当我搜索“结果=一个”时,我可以找到它,而当我尝试搜索“下一个”字符串时,它没有给我任何输出。只有当我独自一人时,它才会给出我需要的确切路线。解决此问题的任何帮助将不胜感激。谢谢

标签: python-3.xlinux

解决方案


您的代码的问题是您continue在 for 循环中使用。continue基本上结束了当前的迭代,所以它不会执行你的if 'next' in line:.

更新文本后,仍然不是很清楚,但是此代码可能会执行您想要的操作。

#! /usr/bin/env python3

import gzip

with gzip.open('result.gz', 'rt') as i:
    find_next = False
    for line in i:
        if not find_next and 'result = one' in line:
            find_next = True
        elif find_next and 'next' in line:
            print(line.strip())

我使用一个名为find_next. 它以False. True找到后设置为result = one。基本上,它会更改状态以查找单词next,直到文件末尾。您可以根据需要调整代码。

编辑了解决方案: OP 在描述中写道,可以在同一个文件中找到“下一个”,但是从我的答案的评论中,“下一个”应该在同一行中:我会在这里使用更容易的正则表达式:

#! /usr/bin/env python3

import gzip
import re

# Find 'result = one' then any characters followed by 'next' till the end of the line.
PATTERN = re.compile("(result = one).+(next).*")

with gzip.open('result.gz', 'rt') as i:
    for line in i:
        if PATTERN.search(line):
            print(line.strip())

推荐阅读