码丁实验室,一站式儿童编程学习产品,寻地方代理合作共赢,微信联系:leon121393608。
1. 打开日志文件
虽然,日志文件的后缀为.log,但是基本上与文本文件没有区别,按照一般读取文本文件的方式打开即可:
fp =open("e:\data.log")fp.close()
应用示例:
fp =open("e:\data.log")for line in fp.readlines(): # 遍历每一行filename = line[:14] # 每行取前14个字母,作为下面新建文件的名称content = line[14:] # 每行取第15个字符后的所有字符,作为新建文件的内容with open("e:\"+filename+".txt","w") as fp2:fp2.write(content+"n")fp.close()
参考链接[1].
2 提取目标信息
日志文件每行字符串由空格分隔,例如对第1个字段(IP、时间等)感兴趣,则使用split()方法对每行字符串进行切片,将第1个子字符串存到列表里,用于下一步处理。
示例代码:
#!/usr/bin/Python# -*- coding: UTF-8 -*-txt = "google#Runoob#Taobao#Facebook"# 第二个参数为 1,返回两个参数列表x = txt.split("#", 1)print x
输出结果:
['google', 'Runoob#Taobao#Facebook']
参考链接[2].
3 统计分析
在上一步骤中,将感兴趣的目标信息存储到列表中,现使用Python统计列表元素出现的次数,参考链接[3]提供了很多实现方法[4],本文使用collections[5]中的most_common()方法。
示例:
from collections import Counterdef counter(arr):return Counter(arr).most_common(2) # 返回出现频率最高的两个数# 结果:[(2, 3), (1, 2)]
参考链接[3-4-5]
4 后记
完整代码(待整理):
# -*- coding: utf-8 -*-"""Created on Thu Apr 11 08:24:02 2019@author: Green"""#import sys#import timefrom collections import Counter#import pyExcelimport xlwtfp =open("d:\aa.log")#print len(fp.readlines()) # 3593512mycount = 0IPlists = []for line in fp.readlines():# control times====================#mycount += 1#if mycount > 100:# break#==================================data = line.split(" ") # 依空格切片IP = data[0]IPlists.append(IP)fp.close()print 'Length of IPlists:', len(IPlists)#IPlists.count()IP_CountResult = Counter(IPlists).most_common()#print IP_CountResult#print '[0][0]', IP_CountResult[0][0]print 'Length of IP_CountResult:', len(IP_CountResult)f = xlwt.Workbook() # Create workbooksheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True) # Create sheetrow0 = [u'IP', u'Count']# Create first rowfor i in range(0,len(row0)):sheet1.write(0, i, row0[i])for i in range(0,len(IP_CountResult)):for j in range(0,len(IP_CountResult[i])):sheet1.write(i+1, j, IP_CountResult[i][j])f.save('d:\IP_CountResult.xls') # Save the file#=====================================# 测试字符串切片(分割)# txt = "Google Runoob Taobao Facebook"# 第二个参数为 1,返回两个参数列表# x = txt.split(" ", 1)# print x[0]#=====================================#filename = line[:14]#content = line[14:]#with open("e:\"+filename+".txt","w") as fp2:# fp2.write(content+"n")
其他拓展应用,见链接[6-9]
另,研究pandas在数据处理、绘图等方面的应用。
参考链接:
[1]python文件操作–分析系统log并提取有效数据: https://blog.csdn.net/qq_30758629/article/details/80766583
[2]菜鸟教程 - Python split()方法: http://www.runoob.com/python/att-string-split.html
[3]Python统计列表元素出现次数: https://blog.csdn.net/weixin_40604987/article/details/79292493
[4]get_frequency: https://github.com/KARL13YAN/learning/blob/master/get_frequency.py
[5]collections官方文档: https://docs.python.org/3/library/collections.html
转自公众号:
Robot404

