利用jieba库画词云
程序员文章站
2022-05-04 11:18:25
from wordcloud import WordCloud import matplotlib.pyplot as plt import jieba # 生成词云 def create_word_cloud(filename): with open('hongloumong.txt',encod ......
from wordcloud import wordcloud
import matplotlib.pyplot as plt
import jieba
# 生成词云
def create_word_cloud(filename):
with open('hongloumong.txt',encoding='utf-8') as f:
text = f.read()
wordlist = jieba.cut(text, cut_all=true) # 结巴分词
wl = " ".join(wordlist)
# 设置词云
wc = wordcloud(
# 设置背景颜色
background_color="black",
# 设置最大显示的词云数
max_words=2000,
# 这种字体都在电脑字体中,一般路径
font_path='msyh.ttc',
height=1200,
width=1600,
# 设置字体最大值
max_font_size=100,
# 设置有多少种随机生成状态,即有多少种配色方案
random_state=100,
)
myword = wc.generate(wl) # 生成词云
# 展示词云图
plt.imshow(myword)
plt.axis("off")
plt.show()
wc.to_file('img_book.png') # 把词云保存下
if __name__ == '__main__':
create_word_cloud('hongloumong')
二、改变图片背景:
from pil import image
import numpy as np
import matplotlib.pyplot as plt
import jieba
# 生成词云
def create_word_cloud(filename):
with open('hongloumong.txt',encoding='utf-8') as f:
text = f.read()
wordlist = jieba.cut(text, cut_all=true) # 结巴分词
wl = " ".join(wordlist)
alice_mask = np.array(image.open('xiaoxiong.jpg'))
# 设置词云
wc = wordcloud(
# 设置背景颜色
background_color="white",
# 设置最大显示的词云数
max_words=2000,
# 这种字体都在电脑字体中,一般路径
font_path='msyh.ttc',
mask=alice_mask,
# 设置字体最大值
max_font_size=100,
# 设置有多少种随机生成状态,即有多少种配色方案
random_state=100,
)
myword = wc.generate(wl) # 生成词云
# 展示词云图
plt.imshow(myword)
plt.axis("off")
plt.show()
wc.to_file('img_book.png') # 把词云保存下
if __name__ == '__main__':
create_word_cloud('hongloumong')
上一篇: 从一片飞地说起的地图画法
下一篇: Vue 父子组件之间的通信