我是Python新手,我遇到了下面需要解决的问题。 我有一个来自Apache Log的日志文件,如下所示:
[01/Aug/1995:00:54:59 -0400] "GET /images/opf-logo.gif HTTP/1.0" 200 32511
[01/Aug/1995:00:55:04 -0400] "GET /images/ksclogosmall.gif HTTP/1.0" 200 3635
[01/Aug/1995:00:55:06 -0400] "GET /images/ksclogosmall.gif HTTP/1.0" 403 298
[01/Aug/1995:00:55:09 -0400] "GET /images/ksclogosmall.gif HTTP/1.0" 200 3635
[01/Aug/1995:00:55:18 -0400] "GET /images/opf-logo.gif HTTP/1.0" 200 32511
[01/Aug/1995:00:56:52 -0400] "GET /images/ksclogosmall.gif HTTP/1.0" 200 3635
我将返回10个请求最多的对象及其传输的累积字节数。我只需要包含成功(HTTP 2xx)响应的GET请求。
因此上述日志将导致:
/images/ksclogosmall.gif 10905
/images/opf-logo.gif 65022
到目前为止,我有以下代码:
import re
from collections import Counter, defaultdict
from operator import itemgetter
import itertools
import sys
log_file = "web.log"
pattern = re.compile(
r'\[(?P<date>[^\[\]:]+):(?P<time>\d+:\d+:\d+) (?P<timezone>[\-+]?\d\d\d\d)\] '
+ r'"(?P<method>\w+) (?P<path>[\S]+) (?P<protocol>[^"]+)" (?P<status>\d+) (?P<bytes_xfd>-|\d+)')
dict_list = []
with open(log_file, "r") as f:
for line in f.readlines():
if re.search("GET", line) and re.search(r'HTTP/[\d.]+"\s[2]\d{2}', line):
try:
log_line_data = pattern.match(line)
path = log_line_data["path"]
bytes_transferred = int(log_line_data["bytes_xfd"])
dict_list.append({path: bytes_transferred})
except:
print("Unexpected Error: ", sys.exc_info()[0])
raise
f.close()
print(dict_list)
此代码打印以下字典列表。
[{'/images/opf-logo.gif': 32511},
{'/images/ksclogosmall.gif': 3635},
{'/images/ksclogosmall.gif': 3635},
{'/images/opf-logo.gif': 32511},
{'/images/ksclogosmall.gif': 3635}]
我不知道如何从这里开始得到结果:
/images/ksclogosmall.gif 10905
/images/opf-logo.gif 65022
此结果基本上是添加了对应于类似键的值,这些键按特定键在desc顺序中出现的次数排序。
注意:我尝试使用colllections.Counter但没有用,在这里我想按密钥发生的次数排序。
任何帮助都将不胜感激。
答案 0 :(得分:8)
您可以使用collections.Counter和update
来添加为每个对象传输的字节数:
from collections import Counter
c = Counter()
for d in dict_list:
c.update(d)
occurrences=Counter([list(x.keys())[0] for x in dict_list])
sorted(c.items(), key=lambda x: occurrences[x[0]], reverse=True)
输出:
[('/images/ksclogosmall.gif', 10905), ('/images/opf-logo.gif', 65022)]
答案 1 :(得分:5)
首先,字典列表对这类数据没有意义。由于每个字典只有一个键值对,因此只需构建一个元组列表(如果想要更多可读性,则构建namedtuples
列表)。
tuple_list.append((path, bytes_transferred))
现在,获得您想要的结果将更加直截了当。我个人使用defaultdict
。
from collections import defaultdict
tracker = defaultdict(list)
for path, bytes_transferred in tuple_list:
tracker[path].append(bytes_transferred)
# {'/images/ksclogosmall.gif': [3635, 3635, 3635], '/images/opf-logo.gif': [32511, 32511]}
print([(p, sum(b)) for p, b in sorted(tracker.items(), key=lambda i: -len(i[1]))])
# [('/images/ksclogosmall.gif', 10905), ('/images/opf-logo.gif', 65022)]
答案 2 :(得分:0)
你可以循环你的dict并将值存储在一个新的dict中:
results = {}
for d in dict_list:
for k, v in d.items():
total = results.get(k, 0) # get previously stored value, 0 if none
results[k] = total + v
答案 3 :(得分:0)
这可能不是最优雅的解决方案,但它会起作用:
freq = {}
with open('test.txt') as f:
lines = f.read().splitlines()
for line in lines:
if 'GET' in line and 'HTTP' in line and '200' in line:
path = line.split()[3]
occur = int(line.split()[-1])
freq[path] = freq.get(path, 0) + occur
frequency = {k: v for k, v in sorted(freq.items(), key=lambda x: x[1])}
因此,对于您提供的日志片段:
print(frequency)
>>> {'/images/ksclogosmall.gif': 10905, '/images/opf-logo.gif': 65022}
答案 4 :(得分:0)
另一个选项,两行
....
path = log_line_data["path"]
if [x for x in range(len(dict_list)) if path in dict_list[x].keys()]:
continue
输出
[{'/images/opf-logo.gif': 32511}, {'/images/ksclogosmall.gif': 3635}]
答案 5 :(得分:0)
如果你想崩溃
[{'/images/opf-logo.gif': 32511},
{'/images/ksclogosmall.gif': 3635},
{'/images/ksclogosmall.gif': 3635},
{'/images/opf-logo.gif': 32511},
{'/images/ksclogosmall.gif': 3635}]
进入字典并使用相同的键总计值:
```
total = {}
for d in all:
for k, v in d.items():
if k in total:
total[k] += v
else:
total[k] = v
print(total)
{'/images/opf-logo.gif': 65022, '/images/ksclogosmall.gif': 10905}