Python生成中文词云

PC环境配置

  • Win10,64位
  • Python 3.5.4
  • Pycharm Community 2019.1

项目创建及相关模块安装

  1. 创建项目文件夹 mywordcloud
  2. 命令行输入:cd mywordcloud
  3. python -m venv virenv
  4. pip install numpy
  5. pip install wordcloud
  6. python -m pip install -U pip setuptools(安装matplotlib失败时,需要先执行该命令)
  7. python -m pip install matplotlib

词云代码示例

分析请看注释

import re
import collections  # 词频统计模块
import numpy as np  # numpy数据处理模块
import jieba  # 中文分词模块
import wordcloud  # 词云展示模块
from PIL import Image  # 图像处理模块
import matplotlib.pyplot as plt  # 图像展示模块

# 给定文件,读取文本
with open('春江花月夜') as fp:
    sentence = fp.read()

# 文本预处理
pattern = re.compile(u'[\t,/。\n.-:;)(??"&quot了”“…我]')  # 定义正则表达式匹配模式,去除文本中标点符号
sentence = re.sub(pattern, '', sentence)  # 将符合模式的字符替换为'', 即去除句子中标点符号

# 文本切割为单词
word_list_cut = jieba.cut(sentence, cut_all=False)  # 精确模式分词,分割中文句子为单词
word_list_filter = []  # 收集分割的单词
remove_words = [u'的', u',', u'和', u'是', u'0403', u' ', u'\u3000']  # 自定义去除词库


for word in word_list_cut:
    if word not in remove_words:
        word_list_filter.append(word)

# 词频统计
word_counts = collections.Counter(word_list_filter)  # 对分词做词频统计
# word_counts_top10 = word_counts.most_common(10)  # 获取前10最高频的词
print(word_counts)
# print(word_counts_top10)

# 词云生成与展示
masque = np.array(Image.open('apple.jpg'))  # 从给定图片获取词云背景
wc = wordcloud.WordCloud(
    font_path='simkai.ttf',  # 设置字体,需要设置为系统存在字体,可查看C:\Windows\Fonts下字体属性
    mask=masque,  # 背景图设置
    max_words=200,  # 最多显示词数
    max_font_size=100  # 字体最大值
)

wc.generate_from_frequencies(word_counts)  # 从单词列表生成词云
image_color = wordcloud.ImageColorGenerator(masque)  # 从背景图建立颜色方案
wc.recolor(color_func=image_color)  # 将词云颜色设置为背景图方案
plt.imshow(wc)  # 显示词云
plt.axis('off')  # 关闭坐标轴
plt.show()  # 显示图像

特别说明

  • 通过with open('春江花月夜') as fp指定文本文件,名称任意,内容任意
  • 通过masque = np.array(Image.open('apple.jpg'))指定产生词云的样例图片,名称任意
  • 生成的词云图片如果产生乱码,需要修改字体font_path='simkai.ttf',具体可查看C:\Windows\Fonts下字体属性

词云图片展示

上方是原图,下方是生成的词云图片

在这里插入图片描述

在这里插入图片描述

发布了53 篇原创文章 · 获赞 20 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/lylfv/article/details/97783890