欢迎访问宙启技术站
智能推送

使用WordCloud库在Python中创建中文词云图

发布时间:2023-12-18 12:55:43

import jieba

from wordcloud import WordCloud

import matplotlib.pyplot as plt

# 读取文本文件

with open('text.txt', 'r', encoding='utf-8') as f:

    text = f.read()

# 使用jieba进行中文分词

words = jieba.cut(text)

# 将分词结果转换为字符串

words_str = ' '.join(words)

# 创建词云对象

wc = WordCloud(font_path='simsun.ttf', # 使用中文字体

               background_color='white', # 设置背景颜色

               width=800, # 设置图片宽度

               height=600 # 设置图片高度

              )

# 生成词云图

wc.generate(words_str)

# 绘制词云图

plt.imshow(wc)

plt.axis('off') # 关闭坐标轴

plt.show()

# 保存词云图到文件

wc.to_file('wordcloud.png')