python处理日志

来源:互联网 发布:淘宝闲鱼在哪找 编辑:程序博客网 时间:2024/05/16 11:39

怎么统计ip出现次数的前10?

python代码如下:

f = open('../www_access_20140823.log')
res = {}
for l in f:
    arr = l.split(' ')
    ip = arr[0]
    url = arr[6]
    status = arr[8]
    res[(ip,url,status)] = res.get((ip,url,status),0)+1
res_list = [(k[0],k[1],k[2],v) for k,v in res.items()]

for k in sorted(res_list,key=lambda x:x[3],reverse=True)[:10]:
    print k

脚本中使用到的方法:

list.spilt()

按照指定的分割符进行切割

list.get(k,d)
get相当于一条if...else...语句,参数k在字典中,字典将返回list[k];如果参数k不在字典中则返回参数d,如果K在字典中则返回k对应的value值;
例子:
l = {5:2,3:4}
print l.get(3,0)返回的值是4;
Print l.get(1,0)返回值是0;

items()

>>> dict = { 1 : 2'a' : 'b''hello' : 'world' } 

>>> dict.values() 

['b'2'world'

>>> dict.keys() 

['a'1'hello'

>>> dict.items() 

[('a''b'), (12), ('hello''world')] 






0 0