itchat的基本使用:
(需要注意的一點是拼接好友頭像導(dǎo)包的時候python3以上版本的需要導(dǎo)入Pillow,以下的導(dǎo)入PIL)
createImg.jpg
getsex.png
signature.png
import itchat
import os
import PIL.Image as Image
from os import listdir
import math
import matplotlib.pyplot as plt
import random
from wordcloud import WordCloud
import re
if __name__ == '__main__':
# 登錄
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)[0:]
# 發(fā)送信息
# for item friends:
# print(item)
# print(item['NickName'])
# number = 500
# while number:
# itchat.send_msg('', friends[20]['UserName'])
# number -= 1
# 爬取拼接圖片
# user = friends[0]["UserName"]
#
# print(user)
#
# os.mkdir(user)
#
# num = 0
#
# for i in friends:
# img = itchat.get_head_img(userName=i["UserName"])
#
# fileImage = open(user + "/" + str(num) + ".jpg", 'wb')
#
# fileImage.write(img)
#
# fileImage.close()
#
# num += 1
#
# pics = listdir(user)
#
# numPic = len(pics)
#
# print(numPic)
#
# eachsize = int(math.sqrt(float(640 * 640) / numPic))
#
# print(eachsize)
#
# numline = int(640 / eachsize)
#
# toImage = Image.new('RGB', (640, 640))
#
# print(numline)
#
# x = 0
#
# y = 0
#
# for i in pics:
#
# try:
#
# # 打開圖片
#
# img = Image.open(user + "/" + i)
#
# except IOError:
#
# print("Error: 沒有找到文件或讀取文件失敗")
#
# else:
#
# # 縮小圖片
#
# img = img.resize((eachsize, eachsize), Image.ANTIALIAS)
#
# # 拼接圖片
#
# toImage.paste(img, (x * eachsize, y * eachsize))
#
# x += 1
#
# if x == numline:
# x = 0
#
# y += 1
#
# toImage.save(user + ".jpg")
#
# itchat.send_image(user + ".jpg", 'filehelper')
# 性別統(tǒng)計
# sex = dict()
# for f in friends:
# if f["Sex"] == 1: # 男
# sex["man"] = sex.get("man", 0) + 1
# elif f["Sex"] == 2: #女
# sex["women"] = sex.get("women", 0) + 1
# else: #未知
# sex["unknown"] = sex.get("unknown", 0) + 1
# # 柱狀圖展示
# for i, key in enumerate(sex):
# plt.bar(key, sex[key])
# plt.show()
# 獲取詞云
itchat.login()
friends = itchat.get_friends(update=True)
file = open('sign.txt', 'a', encoding='utf-8')
for f in friends:
signature = f["Signature"].strip().replace("emoji", "").replace("span", "").replace("class", "")
rec = re.compile("1f\d+\w*|[<>/=]")
signature = rec.sub("", signature)
file.write(signature + "\n")
# 生成詞云圖
def create_word_cloud(filename):
# 讀取文件內(nèi)容
text = open("{}.txt".format(filename), encoding='utf-8').read()
# 注釋部分采用結(jié)巴分詞
# wordlist = jieba.cut(text, cut_all=True)
# wl = " ".join(wordlist)
# 設(shè)置詞云
wc = WordCloud(
# 設(shè)置背景顏色
background_color="white",
# 設(shè)置最大顯示的詞云數(shù)
max_words=2000,
# 這種字體都在電腦字體中,window在C:\Windows\Fonts\下,mac下可選/System/Library/Fonts/PingFang.ttc 字體
font_path='C:\\Windows\\Fonts\\simfang.ttf',
height=500,
width=500,
# 設(shè)置字體最大值
max_font_size=60,
# 設(shè)置有多少種隨機生成狀態(tài)玫荣,即有多少種配色方案
random_state=30,
)
myword = wc.generate(text) # 生成詞云 如果用結(jié)巴分詞的話,使用wl 取代 text, 生成詞云圖
# 展示詞云圖
plt.imshow(myword)
plt.axis("off")
plt.show()
wc.to_file('signature.png') # 把詞云保存下
create_word_cloud("sign")