我正在寫一個腳本,將大的(400mb)apache日誌文件解析到熊貓表中。如何加快使用RegEx解析Apache日誌以擴展Pandas數據框?
我的舊筆記本電腦在大約2分鐘內用腳本解析apache日誌文件。 現在我想知道它不能更快?
Apache的日誌文件的結構是這樣的: 葉 - - [時間戳]「GET ......法」 HTTP狀態代碼字節「地址」,「用戶代理」 例如:
93.185.11.11 - - [13/Aug/2016:05:34:12 +0200] "GET /v1/con?from=…" 200 575 "http://google.com" "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0"
我的代碼使用正則表達式findall。我也測試了匹配和搜索方法。但他們似乎更慢。
reg_dic = {
"ip" : r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b',
"timestamp" : r'\[\d+\/\w+\/\d+\:\d+\:\d+\:\d+\s\+\d+\]',
"method" : r'"(.*?)"',
"httpstatus" : r'\s\d{1,3}\s',
"bytes_" : r'\s\d+\s\"',
"adress" : r'\d\s\"(.*?)"',
"useragent" : r'\"\s\"(.*?)"'
}
for name, reg in reg_dic.items() :
item_list = []
with open (file) as f_obj:
for line in f_obj :
item = re.findall(reg , line)
item = item[0]
if name == "bytes_" :
item = item.replace("\"", "")
item = item.strip()
item_list.append(item)
df[ name ] = item_list
del item_list
參見[這條巨蟒演示(https://ideone.com/LLW3Uf)和[正則表達式演示(https://開頭regex101的.com/R/UOtsAL/1)。如果你的日誌行總是相同的格式,這應該是快速和安全的。 –