python 生成词云

作者: loooooong 分类: python 发布时间: 2020-06-25 05:55
# coding:utf-8
import re


text='''

4:支付宝曝重大安全漏洞:熟人100%可以登录你的支付宝_TechWeb
9:在我们手机丢失时支付宝里面的资金是安全的吗?看完你知道了!
11:注意!你以为你的支付宝账户安全吗?
"


'''

# 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__)
# 更改目录下Wordcloud生成图片,如:xiaohuangren.jpg
alice_coloring = np.array(Image.open(os.path.join(d, "timg.jpeg")))
# win系统需要更改font路径,如:C:\Windows\Fonts\msyhbd.ttc
my_wordcloud = WordCloud(background_color="white",
                         max_words=150,
                         mask=alice_coloring,
                         max_font_size=300,
                         random_state=42,
                         font_path='/Library/Fonts/Microsoft/Microsoft Yahei.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"))

需要配置字体

词云的背景图片可以调整

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

Leave a Reply

Your email address will not be published. Required fields are marked *