python中解析日志文件

2024-09-30 20:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个日志文件,结构如下,需要在python中解析:

10.243.166.74, 10.243.166.74 - - [08/Feb/2017:16:33:26 +0100] "GET /script/header_footer.js?_=1486568008442 HTTP/1.1" 200 2143 "http://www.trendtron.com/popmenu/home" "Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0 K-Meleon/75.1"

我第一次做注册。表情,我得到的只是:

^{pr2}$

这段代码有7个字符串,但我需要更多。 期望输出:

"10.243.166.74, 10.243.166.74"
"08/Feb/2017"
"16:33:26"
"+0100"
"GET /script/header_footer.js?_=1486568008442"
"HTTP/1.1"
"200"
"2143"
"http://www.trendtron.com/popmenu/home"
"Mozilla/5.0"
"(Windows NT 6.1; rv:31.0)"
"Gecko/20100101"
"Firefox/31.0"\
"K-Meleon/75.1"

Tags: comhttpmozillahomegetwindowswwwjs
2条回答

为什么不把最后一组按空格分开呢?在

import re
log = '10.243.166.74, 10.243.166.74 - - [08/Feb/2017:16:33:26 +0100] "GET /script/header_footer.js?_=1486568008442 HTTP/1.1" 200 2143 "http://www.trendtron.com/popmenu/home" "Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0 K-Meleon/75.1"'

regex = re.compile('(.+?)\[(.*?)\] "(.*?)" (\d+) (\d+) "(.*?)" "(.*?)"')
res = regex.match(log)
log_parts = list(res.groups())
devices_browsers_info_str = log_parts.pop(-1)
devices_browsers_info_parts = devices_browsers_info_str.split(' ')
log_parts.extend(devices_browsers_info_parts)

给了我们

^{pr2}$
(.+?)\- - \[(.+?)\:(.+?)\ (.+?)\] \"(.+?)\ (HTTP.+?)\" (.+?) (.+?) \"(.+?)\" \"(.+?) (.+?\)) (.+?)\ (.+?)\ (.+?)\"

或者:http://regexr.com/3fndb

相关问题 更多 >