制作微信好友个性签名词云图是一项很有趣的Python项目。下面是详细的制作攻略。
1. 准备数据
要制作词云图,首先需要获取微信好友的签名数据。可以使用itchat这个Python库来获取微信好友信息。使用以下代码获取微信好友信息并将签名数据保存到文本文件中:
import itchat
# 登录微信
itchat.auto_login()
# 获取好友列表(含详细信息)
friends = itchat.get_friends(update=True)
# 从好友列表中提取签名信息
signature_list = []
for friend in friends:
signature = friend["Signature"].strip().replace("emoji", "")
if signature != "":
signature_list.append(signature)
# 将签名信息保存到文件中
with open("signature.txt", "w", encoding="utf-8") as f:
for signature in signature_list:
f.write(signature + "\n")
2. 分词
接下来需要将签名数据进行分词处理。这里可以使用jieba这个Python库。使用以下代码进行分词:
import jieba
# 读取签名数据
with open("signature.txt", "r", encoding="utf-8") as f:
text = f.read()
# 分词
word_list = jieba.cut(text)
# 将分词结果保存到文件中
with open("word_list.txt", "w", encoding="utf-8") as f:
for word in word_list:
f.write(word + " ")
3. 生成词云图
接下来需要使用词云生成库wordcloud来生成词云图。使用以下代码生成词云图:
import matplotlib.pyplot as plt
from wordcloud import WordCloud
# 读取分词结果
with open("word_list.txt", "r", encoding="utf-8") as f:
text = f.read()
# 生成词云图
wordcloud = WordCloud().generate(text)
# 显示词云图
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
# 保存词云图
wordcloud.to_file("signature_wordcloud.png")
以上是制作微信好友个性签名词云图的完整攻略。下面给出两个示例说明。
示例一
如果你想定制词云图背景颜色和字体,请使用以下代码:
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import jieba
# 读取签名数据
with open("signature.txt", "r", encoding="utf-8") as f:
text = f.read()
# 分词
word_list = jieba.cut(text)
# 读取自定义图片
mask = np.array(Image.open("mask.png"))
# 设置字体路径
font_path = "msyh.ttc"
# 生成词云图
wordcloud = WordCloud(font_path=font_path, mask=mask,
background_color="white", mode="RGBA").generate(text)
color = ImageColorGenerator(mask)
# 显示词云图
plt.imshow(wordcloud.recolor(color_func=color), interpolation="bilinear")
plt.axis("off")
plt.show()
# 保存词云图
wordcloud.to_file("signature_wordcloud_custom.png")
示例二
如果你希望词云图中的词语按照字体大小排序,请使用以下代码:
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import jieba
# 读取签名数据
with open("signature.txt", "r", encoding="utf-8") as f:
text = f.read()
# 分词
word_list = jieba.cut(text)
# 读取自定义图片
mask = np.array(Image.open("mask.png"))
# 设置字体路径
font_path = "msyh.ttc"
# 生成词云图
wordcloud = WordCloud(font_path=font_path, mask=mask, max_words=100,
max_font_size=200, background_color="white", mode="RGBA").generate(text)
color = ImageColorGenerator(mask)
# 显示词云图
fig, ax = plt.subplots()
ax.imshow(wordcloud.recolor(color_func=color), interpolation="bilinear")
ax.axis("off")
# 排序
words = list(wordcloud.words_.keys())
counts = list(wordcloud.words_.values())
idx = np.argsort(np.array(counts))[::-1]
# 生成legend
for i, w in enumerate(np.array(words)[idx][:10]):
ax.text(250, 100+i*50, w, fontsize=20, color="black", ha="center", va="center")
plt.show()
# 保存词云图
wordcloud.to_file("signature_wordcloud_sorted.png")
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:如何用Python制作微信好友个性签名词云图 - Python技术站