日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析

發布時間:2024/6/1 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近準備學習微信小程序開發,偶然間看到了python與微信互動的接口itchat,簡單學習了下,感覺還挺有意思的,故寫了篇基礎文章供大家學習。itchat是一個開源的微信個人號接口,使用python調用微信從未如此簡單。使用不到三十行的代碼,你就可以完成一個能夠處理所有信息的微信機器人。

官網文檔:http://itchat.readthedocs.io/zh/latest/

本文主要講解itchat擴展包的入門基礎知識,包括:
1.itchat安裝及入門知識
2.微信好友性別分析
3.微信自動回復及發送圖片
4.獲取微信簽名并進行詞云分析

基礎性文章,希望對您有所幫助,后面將結合輿情分析、朋友圈等接口進行更一步的講解。如果文章中存在錯誤或不足之處,還請海涵~

參考文章:
https://zhuanlan.zhihu.com/p/26514576?group_id=839173221667446784
https://www.cnblogs.com/jmmchina/p/6692149.html

http://blog.csdn.net/qinyuanpei/article/details/79360703



一. itchat安裝及入門知識


安裝通過 pip install itchat 命令實現,如下圖所示:


安裝成功之后通過 import itchat 進行導入。


下面給出我們第一個簡單的代碼:
# -*- coding:utf-8 -*- import itchat# 登錄 itchat.login() # 發送消息 itchat.send(u'你好', 'filehelper')

首先調用itchat.login()函數登錄微信,再通過itchat.send(u'你好', 'filehelper')函數發送信息給微信的“文件傳輸助手(filehelper)”。注意,執行代碼過程中會彈出一張二維碼圖片,我們通過手機掃一掃登錄后才能獲取我們微信及好友的信息。

??


輸出結果如下圖所示,可以看到給自己發送了一個“你好”。



下面給出另一段代碼:

#-*- coding:utf-8 -*- import itchat# 先登錄 itchat.login()# 獲取好友列表 friends = itchat.get_friends(update=True)[0:] print u"昵稱", u"性別", u"省份", u"城市" for i in friends[0:]:print i["NickName"], i["Sex"], i["Province"], i["City"] 這里最重要的代碼是獲取好友列表,代碼如下:
? ? friends = itchat.get_friends(update=True)[0:]?

再通過["NickName"]獲取昵稱、["Sex"]獲取性別、["Province"]獲取省份、["City"]獲取城市。返回的結果如下所示,其中第一個friends[0]是作者本人,然后性別0表示未填寫、1表示男性、2表示女性;省份和城市可以不設置。




二. 微信好友性別分析


下面直接給出對微信好友性別分析繪圖的代碼:

#-*- coding:utf-8 -*- import itchat#獲取好友列表 itchat.login() #登錄 friends = itchat.get_friends(update=True)[0:]#初始化計數器 male = 0 female = 0 other = 0#1男性,2女性,3未設定性別 for i in friends[1:]: #列表里第一位是自己,所以從"自己"之后開始計算sex = i["Sex"]if sex == 1:male += 1elif sex == 2:female += 1else:other += 1 #計算比例 total = len(friends[1:]) print u"男性人數:", male print u"女性人數:", female print u"總人數:", total a = (float(male) / total * 100) b = (float(female) / total * 100) c = (float(other) / total * 100) print u"男性朋友:%.2f%%" % a print u"女性朋友:%.2f%%" % b print u"其他朋友:%.2f%%" % c#繪制圖形 import matplotlib.pyplot as plt labels = ['Male','Female','Unkown'] colors = ['red','yellowgreen','lightskyblue'] counts = [a, b, c] plt.figure(figsize=(8,5), dpi=80) plt.axes(aspect=1) plt.pie(counts, #性別統計結果labels=labels, #性別展示標簽colors=colors, #餅圖區域配色labeldistance = 1.1, #標簽距離圓點距離autopct = '%3.1f%%', #餅圖區域文本格式shadow = False, #餅圖是否顯示陰影startangle = 90, #餅圖起始角度pctdistance = 0.6 #餅圖區域文本距離圓點距離 ) plt.legend(loc='upper right',) plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標簽 plt.title(u'微信好友性別組成') plt.show()

這段代碼獲取好友列表后,從第二個好友開始統計性別,即friends[1:],因為第一個是作者本人,然后通過循環計算未設置性別0、男性1和女性2,最后通過Matplotlib庫繪制餅狀圖。如下所示,發現作者男性朋友66.91%,女性朋友26.98%。




三. 微信自動回復及發送圖片


微信發送信息調用send()函數實現,下面是發送文字信息、文件、圖片和視頻。

# coding-utf-8 import itchat itchat.login() itchat.send("Hello World!", 'filehelper') itchat.send("@fil@%s" % 'test.text') itchat.send("@img@%s" % 'img.jpg', 'filehelper') itchat.send("@vid@%s" % 'test.mkv') 比如給我的微信文件助手發了個“Hello World”和一張圖片。


如果想發送信息給指定好友,則核心代碼如下:

#想給誰發信息,先查找到這個朋友 users = itchat.search_friends(name=u'通訊錄備注名') #找到UserName userName = users[0]['UserName'] #然后給他發消息 itchat.send('hello',toUserName = userName)
下面這部分代碼是自動回復微信信息,同時在文件傳輸助手也同步發送信息。
#coding=utf8 import itchat import time# 自動回復 # 封裝好的裝飾器,當接收到的消息是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()myUserName = itchat.get_friends(update=True)[0]["UserName"]itchat.run() 運行結果如下圖所示:

??



四. 獲取微信簽名并進行詞云分析


最后給出獲取微信好友的簽名的詞云分析,其friends[i]["Signature"]獲取簽名,最后調用jieba分詞最后進行WordCloud詞云分析。

# coding:utf-8 import itchat import reitchat.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, STOPWORDS, ImageColorGenerator import PIL.Image as Image from scipy.misc import imread from os import path# 讀取mask/color圖片 d = path.dirname(__file__) nana_coloring = imread(path.join(d, "test.png")) # 對分詞后的文本生成詞云 my_wordcloud = WordCloud(background_color = 'white', # 設置背景顏色 mask = nana_coloring, # 設置背景圖片 max_words = 2000, # 設置最大現實的字數 stopwords = STOPWORDS, # 設置停用詞 max_font_size = 50, # 設置字體最大值 random_state = 30, # 設置有多少種隨機生成狀態,即有多少種配色方案 ) # generate word cloud my_wordcloud.generate(wl_space_split) # create coloring from image image_colors = ImageColorGenerator(nana_coloring) # recolor wordcloud and show my_wordcloud.recolor(color_func=image_colors) plt.imshow(my_wordcloud) # 顯示詞云圖 plt.axis("off") # 是否顯示x軸、y軸下標 plt.show()

輸出結果如下圖所示,注意這里作者設置了圖片罩,生成的圖形和那個類似,發現“個人”、“世界”、“生活”、“夢想”等關鍵詞挺多的。



(By:Eastmount 2018-03-19 晚上11點??http://blog.csdn.net/eastmount/?)


總結

以上是生活随笔為你收集整理的[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。