python 练习之读取数据特定字段(四)

共计 1103 个字符,预计需要花费 3 分钟才能阅读完成。

#encoding:utf-8

#数据样例:201.158.69.116 - - [03/Jan/2013:21:17:20 -0600] fwf[-] tip[-] 127.0.0.1:9000 0.007 0.007 MX pythontab.com GET /html/test.html HTTP/1.1 "200" 2426 "http://a.com" "es-ES,es;q=0.8" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"

#access log 文件,客户端 ip,url,状态码 出现的次数 取 top10

log_file = open('/Users/macbookair/python/study/conf/access.log','rt')

log_dist = {}

for log in log_file:

nodes = log.split()

#key 取 客户端 IP,url,以及状态码去掉双引号

key = (nodes[0],nodes[13], nodes[15].replace('"',''))

#查询 log_list 是否有这个 key,没有就返回 0 并且加 1,有就返回 value 并加 1

log_dist[key] = log_dist.get(key , 0) + 1

log_file.close()

#排序

log_list = list(log_dist.items())

#比较 10 次,10 个最大的 value 放在最后面

for j in range(10):

for i inrange(len(log_list) - 1):

#比较的是出现次数,索引为 1 从小到大排序(('201.158.69.116', '/html/test.html', '200'): 32)if log_list[i][1] > log_list[i +1][1]:

#交换

log_list[i],log_list[i +1] = log_list[i +1],log_list[i]

log_stat = open('/Users/macbookair/python/study/conf/access_top10.txt','w')

#top10

for key,value in log_list[-1:-11:-1]:

log_stat.writelines('|{ip:10s} | {url:50s} | {status:5s} | {count:10d} |\n'.format(ip=key[0], url=key[1], status=key[2], count=value ))

log_stat.close()
正文完
 1
caoguojian
版权声明:本站原创文章,由 caoguojian 于2022-05-08发表,共计1103字。
转载说明:除特殊说明外本站文章皆由CGJ发布,转载请注明出处。
一言一句话
-「
评论(没有评论)