python使用jieba生成词云图

from wordcloud import WordCloud
import matplotlib.pyplot as plt

import numpy as np
from PIL import Image

import jieba

# 数据获取
with open("data/x_train.txt",'r', encoding='utf-8')as f:
    text=f.read()

# with open('dream is possible.txt','r',encoding='gbk')as f:
#     text=f.read()
#图片获取
mask=np.array(Image.open("./a.png"))

# 数据清洗
# 屏蔽45
# STOPWORDS.add('45')

font=r'C:\Windows\Fonts\simhei.ttf'
sep_list=jieba.lcut_for_search(text,)
sep_list=" ".join(sep_list)
wc=WordCloud(
    scale=4,#调整图片大小---(如果设置太小图会很模糊)
    font_path=font,#使用的字体库
    max_words=200,  # 词云显示的最大词数
    margin=2,#字体之间的间距
    mask=mask,#背景图片
    background_color='white', #背景颜色
    max_font_size=200,
    # min_font_size=1,
    # stopwords=STOPWORDS, #屏蔽的内容
    collocations=False, #避免重复单词
    width=1600,height=1200 #图像宽高,字间距
)

wc.generate(sep_list) #制作词云
wc.to_file('旅游.jpg') #保存到当地文件

# 图片展示
plt.figure(dpi=100) #通过这里可以放大或缩小
plt.imshow(wc,interpolation='catrom')
plt.axis('off')
plt.show()

根据词频生成了词云图

原文地址:https://www.cnblogs.com/chaogehahaha/p/15612360.html