百度貼吧的數據抓取和分析(二):基礎數據分析 百度貼吧的數據抓取和分析(一):指定條目帖子信息抓取

數據的抓取請移步:百度貼吧的數據抓取和分析(一):指定條目帖子信息抓取html

本教程的代碼託管於github: https://github.com/w392807287/spider_baidu_barpython

本教程中使用的是從某貼吧中抓取的8000條帖子中進行清理後剩下的7405條。git

發帖日期統計

引入庫:github

import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt

 使用pandas讀取csv文件:數組

#指定列名
names = ["帖子id","帖子標題","url","回覆數目","發帖日期","open_id","open_type","做者暱稱","做者性別","做者等級","等級名稱"]
df = pd.read_csv('post_info.csv',names=names)

 數據整理:微信

weekday_list = [datetime.strptime(y,"%Y-%m-%d %H:%M").weekday() for y in df["發帖日期"].values]

 歸一化:iphone

dict_week = {}
for week in weekday_list:
    if week not in dict_week.keys():
        dict_week[week] = 1
    else:
        dict_week[week] += 1

 使用matplotlib畫圖:ide

labels = ["MON","TUES","WED","THUS","FRI","SAT","SUM"]
colors = ['red','yellowgreen','lightskyblue','white','red','yellowgreen','lightskyblue']
plt.pie(list(dict_week.values()),labels=labels,colors=colors,autopct = '%3.1f%%')
plt.axis('equal')
plt.legend()
plt.show()

 結果:函數

由圖咱們能夠看出週六週日的發帖量相對較少,而週二到週五的發帖來相對比較多,大概是由於上課比較無聊喜歡發帖咯?post

介於上面兩個操做(歸一化、畫圖)下面不少地方都須要用到,因此這裏將其封裝成函數.

歸一化,根據參數能夠返回字典,正序、倒序的數組

def norm(_list,get="dict"):
    '''
    對傳進來的list進行歸一化操做
    :param _list: 須要操做的list
    :param get: 返回的方式
    :return: 根據get返回
    '''
    _dict = {}
    for i in _list:
        if i not in _dict.keys():
            _dict[i] = 1
        else:
            _dict[i] += 1
    if get == "dict" or get == 0:
        return _dict
    elif get == "array" or get == 1:
        return np.array(sorted(_dict.items(),key=lambda asd:asd[0]))
    elif get == "_array" or get == -1:
        return np.array(sorted(_dict.items(),key=lambda asd:asd[0],reverse=True))
    elif get == "array2" or get == 2:
        return np.array(sorted(_dict.items(), key=lambda asd: asd[1]))
    elif get == "_array2" or get == -2:
        return np.array(sorted(_dict.items(),key=lambda asd:asd[1],reverse=True))
    else:
        print("請輸入正確的值")
        return None

 畫餅狀圖的函數:

class dictPie:
    '''
    傳入字典畫圖
    '''
    def __init__(self,dict):
        self._dict = dict

    def show(self):
        plt.pie(list(self._dict.values()), labels=list(self._dict.keys()), startangle=90, autopct='%3.1f%%')
        plt.axis('equal')
        plt.legend()
        plt.show()

class arrayPie:
    '''
    傳入數組畫圖
    '''
    def __init__(self,array):
        self._array = array

    def show(self):
        plt.pie(self._array[:,1], labels=self._array[:,0], startangle=90, autopct='%3.1f%%')
        plt.axis('equal')
        plt.legend()
        plt.show()

def show_pie(thing,type = "dict"):
    shows = dict(dict=dictPie,array=arrayPie)
    return shows[type](thing)

 

 使用上述函數

發帖年份的餅狀圖:

year_array = norm([x.split(" ")[0].split("-")[0] for x in df["發帖日期"]],get="array")
show_pie(year_array,type="array").show()

 

抓取的數據是此貼吧前近8000條發帖狀況,因此發帖年份主要集中在今年(2016)和去年(2015),與基本狀況相符。可是在這8000條信息中,2012年的貼子數量卻比2013,2014,2011年的要高出不少,說明2012年可能有一些特殊狀況,好比2012年的精品帖比較多之類的。

發帖月份餅狀圖:

month_array = norm([x.split(" ")[0].split("-")[1] for x in df["發帖日期"]],get="array")
show_pie(month_array,type="array").show()

 

從上圖可看出,對於發帖的月份來說6,7,8,9四個月的發帖量佔了一半多,而1,2,3,4,11,12六個月的發帖量僅有三分之一左右。大概是由於天氣緣由吧。科科,原來天氣冷了大夥的發帖熱情也減低了很多。特別是1月2月,大過年的發帖都是單身狗科科。

發帖星期餅狀圖:

weekday_array = norm([datetime.strptime(y,"%Y-%m-%d %H:%M").weekday() for y in df["發帖日期"].values],get="array")
show_pie(weekday_array,type="array").show()

 

再看,星期幾發帖比較多呢?一週七天分佈仍是相對均勻的,可是就週六週日來說仍是會稍微第一點,畢竟上課比較無聊發帖會多一點科科。

發帖客戶端餅狀圖:

open_id_dict = norm(df["open_id"])
show_pie(open_id_dict,type="dict").show()

 

就發帖客戶端來說,毫無疑問手機端(tbclient)佔領了絕大部分的數據量,剩下的就是網頁(tieba)和wap端。

發帖客戶端類型餅狀圖:

open_type_dict = norm(df["open_type"],get=2)
show_pie(open_type_dict,type="array").show()

 

就客戶端類型而言,安卓理所應當是巨頭,而後就是網頁端(nan),其次是iphone用戶,iphone用戶量感受不止這麼多啊,土豪都不逛貼吧的嘛。剩下的就是一些比較難識別的客戶端,佔少部分。

做者性別餅狀圖:

sex_array = norm(df["做者性別"],get=1)[:3]
show_pie(sex_array,type="array").show()

 

 

其中1爲男,2爲女,3表明該用戶隱藏本身的性別。都說理工的妹子少,這逛貼吧的妹子更是少咯?

做者等級餅狀圖:

level_array = norm(df["做者等級"],get=1)[1:16]
show_pie(level_array,type="array").show()

 

12級是個鴻溝嘛。貌似11級的小夥伴都比較喜歡發帖想要快點到12級嘛。

發帖人統計柱狀圖:

level_array = norm(df["做者暱稱"],get=-2)[:10]
plt.xticks(range(10),level_array[:,0])
plt.xlabel("用戶名",fontproperties=font_simsun)
plt.ylabel("發帖數",fontproperties=font_simsun)
plt.bar(left=range(10),height=[int(x) for x in level_array[:,1]],color = 'g')

plt.show()

 

用戶名隱私因此用戶名的顯示亂碼就沒去解決了,大概就是這個樣子~

回覆數目柱狀圖:

reply_array = norm(df["回覆數目"],get=1)[:-50]
print(reply_array)
plt.bar(reply_array[:,0],reply_array[:,1])
plt.show()

 

在回覆數目的處理中,將後面案例不多的去掉了,回帖量主要集中在0-100之間,人氣不夠啊。。。

24小時發帖分佈:

hour_array = norm([x.split(" ")[1].split(":")[0] for x in df["發帖日期"]],get="array")
plt.xlabel("時段",fontproperties=font_simsun)
plt.ylabel("發帖數",fontproperties=font_simsun)
#show_pie(hour_array,type="array").show()
plt.bar(hour_array[:,0],[int(x) for x in hour_array[:,1]])
plt.show()

 

凌晨時段發帖仍是比較少的,可是深夜發帖量爲啥蹭蹭的長呢,一羣單身狗沒有夜生活科科。。

還有一個分鐘段的發帖分佈,沒啥意義。

 待補充……

歡迎多來訪問博客:http://liqiongyu.com/blog

微信公衆號:

相關文章
相關標籤/搜索