代碼放在這裏:wzyonggege/python-wechat-itchatpython
詞雲那裏能夠換成小黃人圖片git
---------------------------------------------------------------------------------------------------github
最近研究了一些微信的玩法,咱們能夠經過網頁版的微信微信網頁版,掃碼登陸後去抓包爬取信息,還能夠post去發送信息。json
而後發現了itchat這個開源項目,做者是@LittleCoder,已經把微信的接口完成了,大大的方便了咱們對微信的挖掘,如下的功能也經過itchat來實現。windows
安裝itchat這個庫微信
pip install itchat
先來段簡單的試用,實現微信的登陸,運行下面代碼會生成一個二維碼,掃碼以後手機端確認登陸,就會發送一條信息給‘filehelper’,這個filehelper就是微信上的文件傳輸助手。併發
import itchat # 登陸 itchat.login() # 發送消息 itchat.send(u'你好', 'filehelper')
除了登陸和發送消息咱們還能夠這麼來玩,往下走~app
想統計下本身微信裏好友的性別比例,固然也是很簡單,先獲取好友列表,統計列表裏性別計數echarts
import itchat # 先登陸 itchat.login() # 獲取好友列表 friends = itchat.get_friends(update=True)[0:] # 初始化計數器,有男有女,固然,有些人是不填的 male = female = other = 0 # 遍歷這個列表,列表裏第一位是本身,因此從"本身"以後開始計算 # 1表示男性,2女性 for i in friends[1:]: sex = i["Sex"] if sex == 1: male += 1 elif sex == 2: female += 1 else: other += 1 # 總數算上,好計算比例啊~ total = len(friends[1:]) # 好了,打印結果 print u"男性好友:%.2f%%" % (float(male) / total * 100) print u"女性好友:%.2f%%" % (float(female) / total * 100) print u"其餘:%.2f%%" % (float(other) / total * 100)
好看看結果:dom
(好吧,暴露了我男性友人較多的真相~~)
好像不夠直觀,有興趣的朋友能夠加上可視化的展現,我這裏用基於python的Echarts(有機會再細講)
先安裝了
pip install echarts-python
展現比例通常使用百分比圓餅表吧
# 使用echarts,加上這段 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"] del chart.json["yAxis"] chart.plot()
登登登登~
獲取好友列表的時候,返回的json信息中還看到了有個性簽名的信息,腦洞一開,把你們的個性簽名都抓下來,看看高頻詞語,還作了個詞雲。
# coding:utf-8 import itchat # 先登陸 itchat.login() # 獲取好友列表 friends = itchat.get_friends(update=True)[0:] for i in friends: # 獲取個性簽名 signature = i["Signature"] print signature
先所有抓取下來
打印以後你會發現,有大量的span,class,emoji,emoji1f3c3等的字段,由於個性簽名中使用了表情符號,這些字段都是要過濾掉的,寫個正則和replace方法過濾掉
for i in friends: # 獲取個性簽名 signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji", "") # 正則匹配過濾掉emoji表情,例如emoji1f3c3等 rep = re.compile("1f\d.+") signature = rep.sub("", signature) print signature
接來下用jieba分詞,而後製做成詞雲,首先要安裝jieba和wordcloud庫
pip install jieba
pip install wordcloud
代碼
# coding:utf-8 import itchat import re itchat.login() friends = itchat.get_friends(update=True)[0:] 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) # jieba分詞 import jieba wordlist_jieba = jieba.cut(text, cut_all=True) wl_space_split = " ".join(wordlist_jieba) # wordcloud詞雲 import matplotlib.pyplot as plt from wordcloud import WordCloud import PIL.Image as Image # 這裏要選擇字體存放路徑,這裏是Mac的,win的字體在windows/Fonts中 my_wordcloud = WordCloud(background_color="white", max_words=2000, max_font_size=40, random_state=42, font_path='/Users/sebastian/Library/Fonts/Arial Unicode.ttf').generate(wl_space_split) plt.imshow(my_wordcloud) plt.axis("off") plt.show()
運行代碼
這。。好像有點醜,根據wordcloud用法,我能夠找一張圖來生成配色方案,我這裏找了一張微信的logo
修改一下代碼
# wordcloud詞雲 import matplotlib.pyplot as plt from wordcloud import WordCloud, ImageColorGenerator import os import numpy as np import PIL.Image as Image d = os.path.dirname(__file__) alice_coloring = np.array(Image.open(os.path.join(d, "wechat.jpg"))) my_wordcloud = WordCloud(background_color="white", max_words=2000, mask=alice_coloring, max_font_size=40, random_state=42, font_path='/Users/sebastian/Library/Fonts/Arial Unicode.ttf')\ .generate(wl_space_split) image_colors = ImageColorGenerator(alice_coloring) plt.imshow(my_wordcloud.recolor(color_func=image_colors)) plt.imshow(my_wordcloud) plt.axis("off") plt.show() # 保存圖片 併發送到手機 my_wordcloud.to_file(os.path.join(d, "wechat_cloud.png")) itchat.send_image("wechat_cloud.png", 'filehelper')
嗯~好像還能夠,這是Mac下生成的,附一個win10下生成的
接着來實現一個相似qq上的自動回覆,原理就是接收到消息,就發消息回去,同時發一條給文件助手,就能夠在文件助手中統一查看消息。
代碼很簡單,來看看
#coding=utf8 import itchat # 自動回覆 # 封裝好的裝飾器,當接收到的消息是Text,即文字消息 @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()
運行後會保持登陸狀態,開啓自動回覆模式,手機上查看:
固然,除了文字Text信息,還能夠接收圖片(表情包算圖片),語音,名片,地理位置,分享和類型爲Note的信息(就是有人提示類的消息,例如撤回消息),把裝飾器寫成下面形式便可接受,你們能夠試試
@itchat.msg_register(['Map', 'Card', 'Note', 'Sharing', 'Picture'])
學習過程當中遇到什麼問題或者想獲取學習資源的話,歡迎加入學習交流羣626062078,咱們一塊兒學Python!