Grep for a word, and if found print 10 lines before and 10 lines after the pattern match(搜索一个单词,如果找到,则在模式匹配之前打印 10 行和在模式匹配之后打印 10 行)
问题描述
我正在处理一个巨大的文件.我想在该行中搜索一个单词,当找到时,我应该在模式匹配之前打印 10 行和在模式匹配之后打印 10 行.我如何在 Python 中做到这一点?
I am processing a huge file. I want to search for a word in the line and when found I should print 10 lines before and 10 lines after the pattern match. How can I do it in Python?
推荐答案
import collections
import itertools
import sys
with open('huge-file') as f:
before = collections.deque(maxlen=10)
for line in f:
if 'word' in line:
sys.stdout.writelines(before)
sys.stdout.write(line)
sys.stdout.writelines(itertools.islice(f, 10))
break
before.append(line)
使用collections.deque
在匹配前最多保存 10 行,并且 itertools.islice
获取匹配后的下 10 行.
used collections.deque
to save up to 10 lines before match, and itertools.islice
to get next 10 lines after the match.
UPDATE 排除带有 ip/mac 地址的行:
UPDATE To exclude lines with ip/mac address:
import collections
import itertools
import re # <---
import sys
addr_pattern = re.compile(
r'd{1,3}.d{1,3}.d{1,3}.d{1,3}|'
r'[da-f]{2}:[da-f]{2}:[da-f]{2}:[da-f]{2}:[da-f]{2}:[da-f]{2}',
flags=re.IGNORECASE
) # <--
with open('huge-file') as f:
before = collections.deque(maxlen=10)
for line in f:
if addr_pattern.search(line): # <---
continue # <---
if 'word' in line:
sys.stdout.writelines(before)
sys.stdout.write(line)
sys.stdout.writelines(itertools.islice(f, 10))
break
before.append(line)
这篇关于搜索一个单词,如果找到,则在模式匹配之前打印 10 行和在模式匹配之后打印 10 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:搜索一个单词,如果找到,则在模式匹配之前打


基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01