爬了自己的微信,才知道好友都是這樣的!
- 2019 年 10 月 4 日
- 筆記
1
寫在前面的話
資源君在python的玩耍之路上發現python是越來越有趣,竟然還能去爬取微信上的資訊,今天資源君帶大家用python來爬一爬自己的微信好友,爬過之後才知道自己的好友是這樣的!
環境:python + itchat + matplotlib
2
看看微信好友性別比例
大家知道自己微信裡面有多少小哥哥,小姐姐么?今天帶大家來看看自己微信到底有多少小哥哥,小姐姐!
- 首先導入我們需要的包:
import itchat import matplotlib.pyplot as plt
2.登錄微信
# 登錄微信 itchat.login()
3.獲取微信好友的性別,並簡單計算一下微信好友性別:
# 初始化 man = woman = other = total = 0 # 獲取好友 friends = itchat.get_friends(update=True) for item in friends[1:]: if item['Sex'] == 1: man += 1 elif item['Sex'] == 0: woman += 1 else: other += 1 total += 1 # 計算出性別佔比 man_all = float(man)/total*100 woman_all = float(woman)/total*100 other_all = float(other)/total*100
4.這一步就是我們把數據進行可視化操作:
# 可視化操作 labels = 'man', 'woman', 'other' fracs = [man_all, woman_all, other_all] explode = [0, 0, 0] plt.axes(aspect=1) plt.pie(x=fracs, labels=labels, explode=explode, autopct='%3.1f %%', shadow=True, labeldistance=1.1, startangle=90, pctdistance=0.6) plt.show()
5.給大家一張效果圖(看來資源君微信男性朋友居多):

3
來看看好友來自哪些城市
以為只能看性別嗎?當然不是,還可以分析很多東西,再來帶大家來看看我們微信好友都來自哪裡?(這裡只列出排名前三的城市)
- 仍然是導包,這次多了一個pandas,我們這次用柱形圖來展示:
import itchat from pandas import DataFrame import matplotlib.pyplot as plt
2. 仍然是登錄:
# 登錄微信 itchat.login()
3. 處理微信好友的數據,每一行程式碼的說明我都寫在注釋裡面了:
# 獲取朋友列表 friends = itchat.get_friends(update=True) # 利用pandas把數據轉化成DataFrame形式 frame = DataFrame(friends) # 獲取frame數據中的Province的數據 friends_province = frame.Province city_count = friends_province.value_counts() # 排除沒有添加城市的好友 city_count = city_count[city_count.index != ''] # 將數據轉化成list格式 city_list = list(city_count.items()) cityname_list = [] citycount_list = [] for item in city_list: cityname_list.append(item[0]) citycount_list.append(item[1])
4. 利用pandas來進行可視化操作,這個地方由於城市過多,我只選取了排名前三的城市來統計:
name_list = ['hunan', 'guangdong', 'beijing'] num_list = citycount_list[0:3] rects = plt.bar(range(len(num_list)), num_list, color='rgby') # X軸標題 index = [0, 1, 2] index = [float(c) + 0.4 for c in index] plt.ylim(ymax=80, ymin=0) plt.xticks(index, name_list) plt.ylabel("number") # X軸標籤 for rect in rects: height = rect.get_height() plt.text(rect.get_x() + rect.get_width() / 2, height, str(height)+'%', ha='center', va='bottom') plt.show()
5. 效果如下:

資源君在最後祝大家新年快樂!2019年我們一起變強,變富!