程式碼放在這裡:wzyonggege/python-wechat-itchat
詞雲那裡可以換成小小兵圖片
作者是@LittleCoder,已經把微信的介面完成了,大大的方便了我們對微信的挖掘,以下的功能也透過itchat來實現。
安裝itchat這個庫pip install itchat先來段簡單的試用,實現微信的登錄,運行下面代碼會生成一個二維碼,掃碼之後手機端確認登錄,就會傳送一封訊息給'filehelper',這個
filehelper就是微信上的檔案傳輸助手。
import itchat# 登录itchat.login()# 发送消息itchat.send(u'你好', 'filehelper')除了登入和傳送訊息我們還可以這麼來玩,往下走~1. 微信好友男女比例想統計下自己微信裡好友的性別比例,當然也是很簡單,先獲取好友列表,統計列表裡性別計數
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 += 1elif sex == 2:female += 1else: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)好看看結果:
先安裝了
pip install echarts-python展示比例一般使用百分比圓餅表吧
# 使用echarts,加上这段from echarts import Echart, Legend, Piechart = 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()登登登登~
# coding:utf-8import 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-8import itchatimport 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 jiebawordlist_jieba = jieba.cut(text, cut_all=True)wl_space_split = " ".join(wordlist_jieba)# wordcloud词云import matplotlib.pyplot as pltfrom wordcloud import WordCloudimport 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 pltfrom wordcloud import WordCloud, ImageColorGeneratorimport osimport numpy as npimport PIL.Image as Imaged = 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')
#coding=utf8import 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()# 获取自己的UserNamemyUserName = itchat.get_friends(update=True)[0]["UserName"]itchat.run()運行後會保持登入狀態,開啟自動回覆模式,手機上查看:
當然,除了文字Text訊息,還可以接收圖片(表情包算圖片),語音,名片,地理位置,分享和類型為Note的訊息(就是有人提示類別的訊息,例如撤回訊息),把裝飾器寫成下面形式即可接受,大家可以試試看
<code class="language-text">@itchat.msg_register(['Map', 'Card', 'Note', 'Sharing', 'Picture'])</code><br><br><br>
以上是用Python如何玩微信的詳細內容。更多資訊請關注PHP中文網其他相關文章!

使用NumPy創建多維數組可以通過以下步驟實現:1)使用numpy.array()函數創建數組,例如np.array([[1,2,3],[4,5,6]])創建2D數組;2)使用np.zeros(),np.ones(),np.random.random()等函數創建特定值填充的數組;3)理解數組的shape和size屬性,確保子數組長度一致,避免錯誤;4)使用np.reshape()函數改變數組形狀;5)注意內存使用,確保代碼清晰高效。

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增強可讀性,和Boostsperformance.Shere'shore'showitworks:1)較小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

文章討論了由於語法歧義而導致的Python中元組理解的不可能。建議使用tuple()與發電機表達式使用tuple()有效地創建元組。 (159個字符)

本文解釋了Python中的模塊和包裝,它們的差異和用法。模塊是單個文件,而軟件包是帶有__init__.py文件的目錄,在層次上組織相關模塊。

文章討論了Python中的Docstrings,其用法和收益。主要問題:Docstrings對於代碼文檔和可訪問性的重要性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3漢化版
中文版,非常好用

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具