python - 从同一个文件python中找到两个匹配的模式
问题描述
我有一个包含 1000 行的文件,我需要在其中找到匹配的模式,一旦我找到并需要从那里找出下一个匹配模式,而不是从一开始
例子:
match1= Unlock event detected
match2= presence service not connected
.....
.....
10:12:53,presence service not connected
.....
.....
11:12:53, Unlock event detected ----> Matching pattern
.....
.....
11:13:53, presence service not connected ----> next matching pattern
.....
.....
我需要得到 11:12:53 和 11:13:53 而不是 10:12:53
# Collect the list of hits
list_log = []
# opening the file
with open (file,'r', errors='ignore') as f:
lines = f.read().splitlines()
#for loop and find the matching pattern
for l in lines:
if re.findall(r"Unlock event detected", l):
list_log.append(l)
elif re.findall(r'presence service not connected',l):
list_log.append(l)
for ll in list_log:
print(ll)
解决方案
要进入 list_log 您想要的两行,您只需要在登录时放置额外的条件。
import re
list_log = []
# opening the file
with open (file,'r', errors='ignore') as f:
lines = f.read().splitlines()
# find the matching patterns
for l in lines:
if not list_log and re.findall(r"Unlock event detected", l):
list_log.append(l)
elif list_log and re.findall(r'presence service not connected',l):
list_log.append(l)
break
print(*list_log, sep = "\n")
输出(使用您的数据作为文件)
11:12:53, Unlock event detected ----> Matching pattern
11:13:53, presence service not connected ----> next matching pattern
推荐阅读
- mysql - 如何使用 .mylogin.cnf 自动执行 mysqladmin 和 mysql_secure_installation 查询?
- python - 简单递归函数中奇怪的“缩进错误”
- mysql - 带有 Docker 的 Google Cloud SQL 代理抛出连接被拒绝
- javascript - 有没有办法覆盖 Mapbox Geocoder 上的结果事件?
- spring - 为什么我的 return 语句返回 null 结果?
- java - 以下语句在 HashMap 方面有什么区别?
- java - Glassfish 服务器启动时出现异常
- javascript - GraphQL:将数据库列获取到不同的 ObjectType 字段属性
- reactjs - 是否可以更改 Context.Consumer 的显示名称?
- angular - 无法将 html2canvas 中的画布添加到 jspdf addHTML() 方法