练习:微信好友分析
来源:http://www.cnblogs.com/jiaoyu121/p/6944398.html
1.好友性别分布
import itchat itchat.login() #itchat.send(u'你好','filehelper') friends = itchat.get_friends(update=True)[0:] #print len(friends) male = female = other = 0 for i in friends[1:]: sex = i['Sex'] #1男性 2 女性 if sex == 1: male += 1 elif sex == 2: female +=1 else: other += 1 total = len(friends[1:]) #print u'男性好友:'+(float(male)/total)*100 print u'男性好友:%.2f%%'%(float(male)/total*100) print u'女性好友:%.2f%%'%(float(female)/total*100) print u'其他:%.2f%%'%(float(other)/total*100)
输出:
可视化
from echarts import Echart, Legend, Pie chart = Echart(u'%s的微信好友性别比例' % (friends[0]['NickName']), 'from WeChat') chart.use(Pie('WeChat', [{'value': male, 'name': u'男性 %.2f%%' % (float(male) / total * 100)}, {'value': female, 'name': u'女性 %.2f%%' % (float(female) / total * 100)}, {'value': other, 'name': u'其他 %.2f%%' % (float(other) / total * 100)}], radius=["50%", "70%"])) chart.use(Legend(["male", "female", "other"])) del chart.json["xAxis"] #x轴y轴暂时没有隐藏 del chart.json["yAxis"] chart.plot()
输出
2.好友个性签名
tList = [] for i in friends: signature = i["Signature"].replace(" ", "").replace("span", "").replace("class", "").replace("emoji", "") rep = re.compile("1f\d.+") signature = rep.sub("", signature) tList.append(signature) # 拼接字符串 text = "".join(tList) print text import jieba all_words = [] #用词列表 wordlist_jieba = jieba.cut(text, cut_all=True) all_words.extend(set(wordlist_jieba)) #set(data)去除重复的词 from collections import Counter count = Counter(all_words) #统计出现次数,以字典的键值对形式存储,元素作为key,其计数作为value。 result = sorted(count.items(), key=lambda x: x[1], reverse=True) #key=lambda x: x[1]在此表示用次数作为关键字 print type(result) #元组列表 #for word in result: # print word[0], word[1]
输出:
可视化
from pyecharts import WordCloud
data = dict(result)
wordcloud = WordCloud('微信好友个性签名词云',width = 1200,height = 720)
wordcloud.add('test',data.keys(),data.values(),word_size_range = [20,80]) wordcloud.render(r'E:\wordcloud.html')
输出
3.自动回复
import time @itchat.msg_register('Text') def text_reply(msg): # 当消息不是由自己发出的 if not msg['FromUserName'] == myUserName: # 发送提示给文件助手 itchat.send_msg(u"[%s]收到好友@%s 的信息:%s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])), msg['User']['NickName'], msg['Text']), 'filehelper') # 回复给好友 return u'[自动回复]您好,我现在有事不在,一会再和您联系。\n已经收到您的的信息:%s\n' % (msg['Text']) if __name__ == '__main__': itchat.auto_login() # 获取自己的UserName myUserName = itchat.get_friends(update=True)[0]["UserName"] itchat.run()
输出: