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 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:搜索一个单词,如果找到,则在模式匹配之前打
基础教程推荐
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
