#! /usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time : 2019/4/22 16:06
# @Author : lihongwei@integritytech.com.cn
# @Site :
# @File : 词云.py
# @Software : PyCharm
# 导入扩展库
import re # 正则表达式库
import collections # 词频统计库
import numpy as np # numpy数据处理库
import jieba # 结巴分词
import wordcloud # 词云展示库
from PIL import Image # 图像处理库
import matplotlib.pyplot as plt # 图像展示库
# 读取文件
fn = open('1.txt', encoding="utf-8") # 打开文件
string_data = fn.read() # 读出整个文件
fn.close() # 关闭文件
# 文本预处理
rule = re.compile(u"[^a-zA-Z0-9\u4e00-\u9fa5]")
string_data = rule.sub('', string_data)
# 文本分词
seg_list_exact = jieba.cut(string_data) # 精简模式
object_list = list()
remove_words = ["的", "与", "和", "于"] # 自定义去除词库
for word in seg_list_exact: # 循环读出每个分词
if word not in remove_words: # 如果不在去除词库中
object_list.append(word) # 分词追加到列表
# 词频统计
word_counts = collections.Counter(object_list) # 对分词做词频统计
word_counts_top10 = word_counts.most_common(10) # 获取前10最高频的词
# 词频展示
mask = np.array(Image.open('wordcloud.jpg')) # 定义词频背景
wc = wordcloud.WordCloud(
background_color="white",
font_path='C:/Windows/Fonts/simhei.ttf', # 设置字体格式
mask=mask, # 设置背景图
max_words=200, # 最多显示词数
max_font_size=100 # 字体最大值
).generate_from_frequencies(word_counts) # 从字典生成词云
# wc.recolor(color_func=wordcloud.ImageColorGenerator(mask)) # 从背景图建立颜色方案,将词云颜色设置为背景图方案
# wc.to_file("new.jpg") # 生成文件
plt.imshow(wc) # 显示词云
plt.axis('off') # 关闭坐标轴
plt.show() # 显示图像
运行效果图:
原图: