欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用jieba库画词云

程序员文章站 2022-07-09 19:29:01
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')

  利用jieba库画词云

 

 

 

二、改变图片背景:

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')

  利用jieba库画词云