日志的下载地址:http://cdn1.python3.vip/files/py/bysms2.log.zip
日志文件 解压后,发现该文件格式如下
1571713540.9697|API list_order >0.03s|sales_22
1571713569.1041|API list_order >0.05s|sales_3
1571713599.2024|API list_order >0.08s|sales_3
1571713569.1578|API list_order >0.05s|sales_302
1571713571.7784|API list_order >0.1s|sales_29
1571713657.2568|API list_order >0.5s|sales_576
1571713657.4442|API list_order >1s|sales_845
该日志文件记录了 服务端对 各个请求处理 耗费的时间信息。
每行以 | 为分隔符, 记录了3个信息:
时间戳
什么请求处理时间大于多少秒
请求对应的用户
要求你写一个程序,统计
(所有,代码不能写死 ,要动态的碰到一种,添加一种统计)
请求处理时间 在 各个时间段的数量,结果格式如下:
API list_order >0.03s : 548个
API list_order >0.05s : 274个
API list_order >0.1s : 306个
API list_order >0.08s : 105个
API list_order >0.5s : 157个
API list_order >1s : 2062个
响应超时 : 403个
伪代码 (思路:)
1 打开文件读取字符串 open()
2 按行读取(按钮换行符切割),返回结果是一个列表 read().splitlines()
3 遍历循环取出元素 for
3.1 去除左右空格=拿到的结果:字符串
3.2 判断空行=拿到的结果:字符串
# 接下来将字符串 转换成 列表
3.3 split切割,得到一个个列表
4 取出列表中infoList[0]-姓 判断是否存在
定义一个计数器
如果不存在就加入字典中,计数器+1
如果存在修改,追加coin值字典中 ,计数器 +1
with open('2019-10-22_11.05.40.log',encoding='utf8') as f:
infoList = f.read().splitlines()
# 定义字典存储统计的数据
infoDic = {}
# for循环遍历列表
for info in infoList:
# 去除左右空格
info = info.strip()
# 去除空行
if not info:
continue
# 按照‘|’切割
infoSplit = info.split('|')
kName = infoSplit[1]
# 计数器
coin = 1
if infoSplit[1] not in infoDic:
# 将name作为key 分数作为value
infoDic[infoSplit[1]] = coin
else:
infoDic[infoSplit[1]] += coin
# 循环获取字典的数据
for k,v in infoDic.items():
print(f'{k} : {v} 个')