python分析nginx日志的ip(中篇一)
2019獨角獸企業重金招聘Python工程師標準>>>
?利用python的數據分析pandas,numpy,matplotlib模塊進行可視化分析,畫出圖表,這幾個模塊需要獨立安裝,安裝好后需要用ipython --pylab方式打開。并且要引用MySQLdb模塊,為了省事,我把數據統計這一塊直接在mysql數據庫中執行了,本身需求就不復雜,況且對pandas,matplotlib這幾個工具也剛接觸不久,持續深入研究中,能簡則簡了。
?
具體步驟如下,切記打開方式用 ipython --pylab
In [1]: from pandas import DataFrame,Series???
In [2]: import pandas as pd
In [3]: import numpy as np???
In [4]: import MySQLdb
#引入python數據分析模塊
In [5]:? mysql_cn= MySQLdb.connect(host='localhost', port=3306,user='root', passwd='root', db='testdb',charset='utf8')
df = pd.read_sql('select count(1) as city_count_num,city from memory group by city order by city_count_num desc limit 10',mysql_cn)
#連接數據庫,轉換成pandas格式的數據
In [7]:? df.index=['suzhou','shanghai','shenzhen','weizhi','qingdao','fuzhou','foshan','changchun','kunming','beijing']
#重建索引,這一步本來不需要的,本來打算是用名字做索引,利用value_counts轉換可以直接畫圖,可死活是亂碼,迫不得已,多此一舉了。大家主要就看“氣質”吧。
In [8]: df.plot(kind='barh',rot=0)
Out[8]: <matplotlib.axes._subplots.AxesSubplot at 0x7f8fb5148390>
#畫圖完成
In [9]: df????????????? #重建索引,轉換后的文件格式如下
Out[9]:
?????????? num city
suzhou???? 520? 蘇州市
shanghai?? 374? 上海市
shenzhen?? 118? 深圳市
weizhi???? 104?? 未知????? #國外的ip,在數據庫中是空的,我設置為“未知”了
qingdao???? 82? 青島市
fuzhou????? 81? 福州市
foshan????? 81? 佛山市
changchun?? 78? 長春市
kunming???? 76? 昆明市
beijing???? 76? 北京市
轉載于:https://my.oschina.net/luoyedao/blog/545722
總結
以上是生活随笔為你收集整理的python分析nginx日志的ip(中篇一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Apache配置静态缓存
- 下一篇: python scoket、Socket