1. __init__ 初始化文件路徑,關鍵字1,關鍵字2;
2. key_match 使用with open 方法,以二進制方式(也可以改成utf-8,GB2312)讀取文件內容(支持txt/log格式);
3. buffer = f.read() 一致性讀取到buffer中,讀取超大文件會發生MemoryError(可以設置每次讀取的size或切割文件)。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
#文本所在路徑,引號前加r指按路徑處理
#關鍵字word1,word2,換關鍵字,需修改引號間的內容
class match2Words(object):
lines=0
def __init__(self,path,word1,word2):
self.path = path
self.word1 = word1
self.word2 = word2
def key_match(self):
with open(self.path,'rb') as f:
buffer = f.read()
pattern = re.compile(self.word1+b'(.*?)'+self.word2,re.S)
result = pattern.findall(buffer)
if result != []:
print(result)
#self.lines +=1
#print("匹配到的行數:",self.lines)
else:
print("沒有找到你輸入的關鍵字")
path = input("請輸入要分析的log地址:")
word1 = b"begin"
word2 = b"end"
matchWords = match2Words(path, word1, word2)
matchWords.key_match()