简介:本文详细介绍了Python词云制作中停用词的概念、作用及常用处理方法,包括内置停用词库的使用、自定义停用词设置以及基于词频和词性的高级过滤技巧,帮助开发者优化词云效果。
词云(Word Cloud)是一种文本数据可视化技术,通过不同大小、颜色和排列方式的文字展示文本中的关键词汇。在Python生态中,wordcloud
库是最常用的词云生成工具。
停用词(Stop Words)是指在文本分析中被过滤掉的常见词汇,如”的”、”是”、”在”等。这些词出现频率高但携带信息量低,过滤后能:
wordcloud
库内置了英文停用词集合,可通过STOPWORDS
对象调用:
from wordcloud import WordCloud, STOPWORDS
# 使用内置英文停用词
wc = WordCloud(stopwords=STOPWORDS)
由于中文的特殊性,需要额外处理:
jieba
、snownlp
)示例代码:
from wordcloud import WordCloud
import jieba
# 加载中文停用词
with open('chinese_stopwords.txt', encoding='utf-8') as f:
stopwords = set(f.read().splitlines())
# 结合分词使用
text = ' '.join([word for word in jieba.cut(text) if word not in stopwords])
wc = WordCloud(font_path='simhei.ttf', stopwords=stopwords)
通过设置max_words
和min_font_size
参数控制显示词汇:
wc = WordCloud(
max_words=200, # 最大显示词数
min_font_size=10, # 最小字体大小
stopwords=stopwords
)
结合NLP工具进行词性标注过滤:
import jieba.posseg as pseg
words = pseg.cut(text)
filtered_words = [word for word, flag in words
if flag in ['n', 'v', 'a']] # 只保留名词、动词、形容词
使用正则表达式处理特殊字符和数字:
import re
text = re.sub(r'\d+', '', text) # 去除数字
# 完整示例
from wordcloud import WordCloud
import jieba
import matplotlib.pyplot as plt
# 1. 加载数据与停用词
text = open('reviews.txt', encoding='utf-8').read()
stopwords = set(open('stopwords.txt', encoding='utf-8').read().splitlines())
# 2. 分词与过滤
words = [word for word in jieba.cut(text)
if word not in stopwords and len(word) > 1]
# 3. 生成词云
wc = WordCloud(
font_path='msyh.ttc',
background_color='white',
max_words=300,
stopwords=stopwords
).generate(' '.join(words))
plt.imshow(wc)
plt.axis('off')
plt.show()
mask
参数指定蒙版图片结合Flask等框架实现Web端动态词云:
from flask import Flask, request
import io
import base64
@app.route('/wordcloud', methods=['POST'])
def generate_wordcloud():
text = request.form['text']
img = io.BytesIO()
wc.to_image().save(img, format='PNG')
return base64.b64encode(img.getvalue()).decode()
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(stop_words=list(stopwords))
tfidf_matrix = tfidf.fit_transform([text])
word_weights = dict(zip(tfidf.get_feature_names_out(),
tfidf_matrix.toarray()[0]))
# 传入频率字典
wc.generate_from_frequencies(word_weights)
停用词库选择:
处理流程建议:
graph TD
A[原始文本] --> B[数据清洗]
B --> C[分词处理]
C --> D[停用词过滤]
D --> E[词性过滤]
E --> F[词频统计]
F --> G[生成词云]
性能优化技巧:
通过合理的停用词设置和词过滤技术,可以显著提升Python词云的分析效果和视觉表现力。建议开发者根据具体场景灵活组合多种过滤方法,并持续优化停用词库。