python-3.x - 如何在单个 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)
当我搜索“结果=一个”时,我可以找到它,而当我尝试搜索“下一个”字符串时,它没有给我任何输出。只有当我独自一人时,它才会给出我需要的确切路线。解决此问题的任何帮助将不胜感激。谢谢
解决方案
您的代码的问题是您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())
推荐阅读
- javascript - 使用 JavaScript 在多个 HTML 输入字段值之间进行动态线性插值
- flutter - 我们如何在颤振中实现这样的东西?
- c++ - 当参数作为右值传递时,完美转发避免复制?
- python - 如何分解条件的数据框行?
- reporting-services - SSRS - tablix 中的第一行边框未加粗
- jquery - 首先在给定的行对象中插入列
- c - 未分配的#defines 是否隐式分配为 0?
- python-3.x - 根据另一列的值在数据框的列上应用函数,然后按 groupby
- excel - 将 excel 转换为特定类型的 XML 格式?
- git - 如何将 core.sshCommand 选项传播到子模块更新?