以《神雕侠侣》为例,我们制作词云,看看有哪些高频词汇。
1. 导入一些包
# -*- coding:utf-8 -*-
# @Python Version: 3.7
# @Time: 2020/11/27 19:32
# @Author: Michael Ming
# @Website: https://michael.blog.csdn.net/
# @File: word_cloud.py
# @Reference: import jieba
import numpy as np
from PIL import Image
from wordcloud import WordCloud
2. 文本处理
- 去掉一些空白的字符
\n, \t, ' '
等 jieba.cut
分词- 屏蔽停用词,以及长度小于2的词
stopwords = []
with open("stopwords.txt", 'r', encoding='utf-8') as f:for w in f:stopwords.append(w.replace('\n', ''))with open('processed_txt.txt', 'w', encoding='utf-8') as processed:words_list = []with open("../shendiaoxialv.txt", 'r', encoding='utf-8') as f:for line in f:word = jieba.cut(line.replace('\t', '').replace('\n', '').replace(' ', ''))for w in word:if w not in stopwords and len(w) > 1:words_list.append(w)processed.write(' '.join(words_list))
3. 制作词云
# 读取清理好了以后的词
wordtxt = ""
with open('processed_txt.txt', 'r', encoding='utf-8') as f:wordtxt = f.read()# 设置背景图片,也可以没有
background_pic = np.array(Image.open('background.png'))
wc = WordCloud(background_color='white', # 背景色max_words=300, # 最多词语数量font_path='wb.ttf', # 字体min_font_size=12, # 最小字号max_font_size=52, # 最大字号width=1600, # 图片宽度height=1200, # 图片高度mask=background_pic # 背景形状
)wc.generate(wordtxt)
wc.to_file("wc.jpg")
使用以下背景图片:
生成词云:
可以看见 杨过
和 小龙女
是最显眼的两个词语,也是小说的主角。
再换一个背景图片:
调节最小10号字,最大100号的字,生成词云: