1. 程式人生 > >使用Python 統計nginx日誌前十ip訪問量並以柱狀圖顯示

使用Python 統計nginx日誌前十ip訪問量並以柱狀圖顯示

指令碼內容:

    import matplotlib.pyplot as plt
#
nginx_file = '10.6.11.91_access.log-2018-12-27'

ip = {}
#篩選nginx日誌檔案中的IP
with open(nginx_file) as f:
    for i in f.readlines():
        s = i.strip().split()[0]
        lengh = len(ip.keys())
    
        #統計每個IP的訪問以字典儲存
        if s in ip.keys():
            ip[s] = ip[s] + 1
        else:
            ip[s] = 1
        
#以IP出現的次數排序返回物件為list
ip = sorted(ip.items(), key=lambda e:e[1], reverse=True)

#取列表前十
newip = ip[0:10:1]
tu = dict(newip)

x = []
y = []
for k in tu:
    x.append(k)
    y.append(tu[k])
plt.title('ip access')
plt.xlabel('ip address')
plt.ylabel('pv')

#X 軸項的翻轉角度
plt.xticks(rotation=70)

#顯示每個柱狀圖的值
for a,b in zip(x,y):
    plt.text(a, b, '%.0f' % b, ha='center', va= 'bottom',fontsize=7)
    
plt.bar(x,y)
plt.legend()
plt.show()

效果: