博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python处理日志
阅读量:2196 次
发布时间:2019-05-02

本文共 711 字,大约阅读时间需要 2 分钟。

怎么统计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')] 

转载地址:http://ampub.baihongyu.com/

你可能感兴趣的文章
【LEETCODE】27-Remove Element
查看>>
【LEETCODE】66-Plus One
查看>>
【LEETCODE】26-Remove Duplicates from Sorted Array
查看>>
【LEETCODE】118-Pascal's Triangle
查看>>
【LEETCODE】119-Pascal's Triangle II
查看>>
【LEETCODE】88-Merge Sorted Array
查看>>
【LEETCODE】19-Remove Nth Node From End of List
查看>>
【LEETCODE】125-Valid Palindrome
查看>>
【LEETCODE】28-Implement strStr()
查看>>
【LEETCODE】6-ZigZag Conversion
查看>>
【LEETCODE】8-String to Integer (atoi)
查看>>
【LEETCODE】14-Longest Common Prefix
查看>>
【LEETCODE】38-Count and Say
查看>>
【LEETCODE】278-First Bad Version
查看>>
【LEETCODE】303-Range Sum Query - Immutable
查看>>
【LEETCODE】21-Merge Two Sorted Lists
查看>>
【LEETCODE】231-Power of Two
查看>>
【LEETCODE】172-Factorial Trailing Zeroes
查看>>
【LEETCODE】112-Path Sum
查看>>
【LEETCODE】9-Palindrome Number
查看>>