1. 程式人生 > >python 微信生成詞雲(itchat,jieba,wordcloud)

python 微信生成詞雲(itchat,jieba,wordcloud)

  • 完整程式碼:
import itchat
import re#正則匹配
# 先登入,掃二維碼登入微信
itchat.login()
#獲取好友列表,返回的是json資訊
friends = itchat.get_friends(update=True)[0:]
#列印好友列表資訊
#print(friends)
tList = []
for i in friends:
    # 獲取個性簽名,替換掉span,class,emoji
    signature = i["Signature"].replace(" ", "").replace("span", "")
.replace("class", "").replace("emoji", "") # 正則匹配過濾掉emoji表情,例如emoji1f3c3等 rep = re.compile("1f\d.+")#建立正則匹配物件 signature = rep.sub("", signature)#用signature替換空格 tList.append(signature) # 拼接字串 text = "".join(tList)
    Getting uuid of QR code.
    Downloading QR code.
    Please scan the QR code to log in
. Please press confirm on your phone. Loading the contact, this may take a little while. Login successfully as 孤久則慣

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, ImageColorGenerator import os import numpy as np import PIL.Image as Image #d = os.path.dirname(__file__) #找一張微信logo圖來生成配色方案,微信logo圖wechat.jpg路徑在F:\\盤下 alice_coloring = np.array(Image.open(os.path.join('2.jpg'))) #這裡要選擇字型存放路徑,win的字型在C:/windows/Fonts中 # """#my_wordcloud = WordCloud().generate(wl_space_split) 預設建構函式 # my_wordcloud = WordCloud( # background_color='white', # 設定背景顏色 //這邊的顏色可以修改成很多= =就是詞雲所在圖的後面的顏色 # mask = abel_mask, # 設定背景圖片 # max_words = 200, # 設定最大顯示的字數 # stopwords = STOPWORDS, # 設定停用詞 # font_path = C:/Users/Windows/fonts/simkai.ttf', # 設定字型格式,如不設定顯示不了中文 # max_font_size = 50, # 設定字型最大值 # random_state = 30, # 設定有多少種隨機生成狀態,即有多少種配色方案 # scale=.5 # ).generate(wl_space_split)""" my_wordcloud = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,max_font_size=40, random_state=42,font_path='C:/Windows/Fonts/simhei.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() # 儲存圖片到F:\\盤下 併發送到手機裡的檔案傳輸助手(filehelper)裡 my_wordcloud.to_file(os.path.join('wechat_cloud.png')) itchat.send_image("wechat_cloud.png", 'filehelper')
<ItchatReturnValue: {'MsgID': '771396254817770412', 'BaseResponse': {'RawMsg': '請求成功', 'Ret': 0, 'ErrMsg': '請求成功'}, 'LocalID': '15432908217370'}>

//配色圖的意思是以所用圖的顏色和基礎形狀為基準生成詞雲的圖片,字型大小為出現的頻率多少
在這裡插入圖片描述

在這裡插入圖片描述

for each in friends:
    print(each['NickName']+" "+str(each['Sex']))
孤久則慣 1
after all. 1
...

tips:
博主所用的配色圖
在這裡插入圖片描述
在這裡插入圖片描述

參考:Eileen0214大大, https://blog.csdn.net/Eileen0214/article/details/80051326