gpt4 book ai didi

python - 在 Python 中集成 grep

转载 作者:太空宇宙 更新时间:2023-11-03 15:50:38 25 4
gpt4 key购买 nike

我正在尝试学习一点Python,我的目标是打开gzip文件,输入搜索查询然后打印出来,最终将结果输出到文件中。

import gzip
file = raw_input('Input Filepath: ') # input file path
with gzip.open(file, 'rb') as f: # opens gzip fil .gz
file_content = f.read() # reads the contents
grep = raw_input('Enter Search: ') # grep asks for output
print(file_content) # prints it in console

我也尝试过使用 print(file_content, grep),但它只返回第一个查找结果。

最佳答案

grep 实用程序将搜索与给定模式匹配的行。

要在 python 中执行此操作,您需要逐行读取文件,然后在每一行中搜索您想要查找的字符串:

import gzip

matched_lines = []
file = raw_input('Imput Filepath: ')
with gzip.open( file, 'rb') as f:
grep = raw_input('Enter Search: ')
for line in f: # read file line by line
if grep in line: # search for string in each line
matched_lines.append(line) # keep a list of matched lines

file_content = ''.join(matched_lines) # join the matched lines

print(file_content)

关于python - 在 Python 中集成 grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41335536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com