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 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:搜索一个单词,如果找到,则在模式匹配之前打


基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01