環(huán)境:win10+python3.6
1.python抓取微信好友數(shù)量及好友比例
使用itchat庫對微信進行操作
登錄微信,跳出一個二維碼潜腻,掃描即可登錄成功
itchat.login()
但是存在的問題就是:每次運行都需要掃碼登錄刽沾,故可以使用另一個方法
itchat.auto_login(hotReload=True)
除第一次登陸需要掃碼外耳贬,后面只需要在手機確定登陸就行
獲取自己好友的相關(guān)信息污筷,得到一個json數(shù)據(jù)返回
data=itchat.get_friends(update=True)
打印之后,發(fā)現(xiàn)有很多數(shù)據(jù)信息桥氏,如備注温峭,昵稱,城市信息字支,簽名等凤藏。
通過sex鍵得到好友男女數(shù)量及比例
itchat.login()
text = dict()
numbers=itchat.get_friends(update=True)
print(len(numbers))
friedns = itchat.get_friends(update=True)[0:]
print(numbers)
print(friedns)
male = "male"
female = "female"
other = "other"
for i in friedns[1:]:
sex = i['Sex']
if sex == 1:
text[male] = text.get(male, 0) + 1
elif sex == 2:
text[female] = text.get(female, 0) + 1
else:
text[other] = text.get(other, 0) + 1
total = len(friedns[1:])
print('男性好友數(shù)量:',text[male])
print('女性好友數(shù)量:',text[female])
print('未知性別好友數(shù)量:',text[other])
print("男性好友比例: %.2f%%" % (float(text[male]) / total * 100) + "\n" +
"女性好友比例: %.2f%%" % (float(text[female]) / total * 100) + "\n" +
?
"不明性別好友比例: %.2f%%" % (float(text[other]) / total * 100))
最后得到自己好友情況如下
使用matplotlib庫來實現(xiàn)微信好友男女比例柱狀圖顯示
from matplotlib import pyplot as plt
?
?
def draw(datas):
for key in datas.keys():
plt.bar(key, datas[key])
?
plt.legend()
plt.xlabel('sex')
plt.ylabel('rate')
plt.title("Gender of Alfred's friends")
圖形顯示如下
這里柱狀圖顯示卻沒有顯示具體數(shù)值,查閱之后發(fā)現(xiàn)可以使用plt.text()來實現(xiàn)在柱狀圖的上方顯示數(shù)值堕伪。
具體的代碼修改如下
def draw(datas):
b=[]
for key in datas.keys():
plt.bar(key, datas[key])# 柱狀圖
b.append(datas[key])
?
a = datas.keys()
# 使用plt.text()來實現(xiàn)柱狀圖顯示數(shù)值
for x, y in zip(a, b):
plt.text(x, y, str(y), ha='center', va='bottom', fontsize=11)
?
plt.legend()
plt.xlabel('sex')
plt.ylabel('rate')
plt.title("Gender of Alfred's friends")
plt.show()
修改后的圖形顯示
項目地址為: