源码
import itchat
import matplotlib.pyplot as plt
import matplotlib
class MyItchat(object):
def __init__(self):
pass
def get_friends_sex(self,friends_list):
'''获取性别数据'''
sex = [0,0,0]
for friend in friends_list[1:]:
if friend["Sex"] == 1:
sex[0] +=1
elif friend["Sex"] == 2:
sex[1] += 1
else:
sex[2] += 1
return sex
def get_city(self,friends_list):
city = {"未填写":0}
for friend in friends_list[1:]:
city_name = friend["City"]
if city_name == '':
city['未填写'] += 1
elif city_name not in city.keys():
city[city_name] = 1
else:
city[city_name] +=1
print(city)
return city
def darw_city(self,city_dict):
name,num = [],[]
citys = sorted(city_dict.items(),key= lambda item : item[1],reverse = True)[0:10]
for city in citys :
name.append(city[0])
num.append(city[1])
rect = plt.bar(name,num,width=0.5,color = 'b')
plt.xlabel('城市名')
plt.ylabel('好友数量')
plt.title('好友城市排名图')
for rec in rect:
height = rec.get_height()
plt.text(rec.get_x()+rec.get_width()/2,height +1,str(height),ha="center", va="bottom")
plt.show()
def darw_sex(self,sex_list):
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
label_list = ["男性","女性","未注明性别"]
color = ["red", "green", "blue"]
explode = [0.05, 0, 0]
plt.pie(sex_list, explode=explode, colors=color, labels=label_list, labeldistance=1.1, autopct="%1.1f%%",
shadow=False, startangle=90, pctdistance=0.6)
plt.axis("equal")
plt.legend()
plt.show()
def run(self):
itchat.auto_login()
my_friends = itchat.get_friends(update=True)
sex_list = self.get_friends_sex(my_friends)
print(sex_list)
self.darw_sex(sex_list)
city_dict = self.get_city(my_friends)
self.darw_city(city_dict)
if __name__ == '__main__':
it_chat = MyItchat()
it_chat.run()
citys = sorted(city_dict.items(),key= lambda item : item[1],reverse = True)[0:10]
itchat 其他方法