Python错误日志模式匹配
我是一名刚接触Python的新手,想要通过实际操作来学习。我正在写一个函数,用来提取特定模式之间的内容。我的日志文件结构如下:
<Time-stamp>[Begin cache] <...Some content>
<Time-stamp>.
<Time-stamp>.
<Time-stamp>.
<Time-stamp>.
<Time-stamp>[ERROR] <..Some content>
<Time-stamp>.
<Time-stamp>.
<Time-stamp>.
<Time-stamp>.
<Time-stamp>[End cache] <....some content>
<Time-stamp>.
<Time-stamp>.
<Time-stamp>.
<Time-stamp>[Begin cache] <... Some content>
<Time-stamp>.
<Time-stamp>.
<Time-stamp>.
<Time-stamp>[End cache] <... Some content>
我想提取“开始缓存”和“结束缓存”之间的部分,前提是这两者之间有一个“错误”的标记。我目前写的代码根本无法达到这个目标。我用的逻辑是先找到“开始缓存”和“结束缓存”的位置,如果中间有“错误”这个标记,就打印出这两个位置之间的内容。任何帮助都会非常感谢。
import re
import os
import mmap
File="\\\\XXXXX\c$\EGO\soam\work\XXXX_20140307.03\dal_XXXX_YYYY_20140320_110536_21_6508.log"
with open(File,"r") as file:
m=mmap.mmap(file.fileno(),0,access=mmap.ACCESS_READ)
mpattern="\[ERROR\]"
spattern="Begin cache"
epattern="End cache"
mregexp=re.compile(mpattern)
sregexp=re.compile(spattern)
eregexp=re.compile(epattern)
for match in sregexp.finditer(m):
epos=eregexp.match(m,match.end())
if mregexp.match(m,match.end(),epos):
print("%s"%(m,match.start(),epos))
我也希望能找到一些好的教程,帮助我快速入门这个既简单又让人困惑的语言。
1 个回答
0
你可以直接在日志文件中查找[ERROR],然后获取需要的文本,正则表达式只是用来分割从日志文件中读取的数据。我建议你使用这个示例方法:
编辑:在数据格式改变后:
使用正则表达式:\[[^R]\w+\s\w+\] 来分割列表,并查看ERROR部分,就像这个例子:
import re
f = open('logfile', 'r')
data = f.read()
f.close()
mylist = re.split(r'\[[^R]\w+\s\w+\]',data)
for item in mylist:
if '[ERROR]' in item:
print item
编辑:
这里有一些地方可以帮助你更好地学习Python:
希望这对你有帮助。