Python 中文评论词云生成:去除干扰词,提高关键词提取效果
由于评论内容中存在很多'啊'、'的'、'了'等无意义的干扰词,影响高频词的提取,因此,采用哈工大停用词表作为停用词词典,对干扰词进行屏蔽,并绘制词云图。
要实现这个功能,可以按照以下步骤进行操作:
- 下载哈工大停用词表 (stopwords.txt),保存在本地。
- 导入所需的库,包括
jieba用于中文分词,wordcloud用于生成词云图。 - 读取评论内容,并进行分词。
- 加载停用词词典。
- 根据停用词词典,过滤掉干扰词。
- 统计词频,并生成词云图。
下面是完整的 Python 代码示例:
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取评论内容
comment = '这个产品真的很好用啊,效果很棒的了。非常喜欢!'
# 进行中文分词
seg_list = jieba.cut(comment, cut_all=False)
# 加载停用词词典
stopwords_path = 'stopwords.txt'
stopwords = set()
with open(stopwords_path, 'r', encoding='utf-8') as f:
for line in f.readlines():
stopwords.add(line.strip())
# 过滤掉干扰词
filtered_words = [word for word in seg_list if word not in stopwords]
# 统计词频
word_count = {}
for word in filtered_words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 生成词云图
wordcloud = WordCloud(font_path='simhei.ttf', background_color='white').generate_from_frequencies(word_count)
# 显示词云图
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
在代码中,我们使用 jieba.cut 函数对评论内容进行分词,然后通过遍历分词结果,过滤掉停用词,统计词频。最后使用 WordCloud 类生成词云图,并使用 matplotlib.pyplot 库显示词云图。
注意:需要提前安装 jieba 和 wordcloud 库,并将停用词词典 (stopwords.txt) 放在正确的路径下。另外,为了能够正确显示中文字符,需要下载并指定一个中文字体(如“simsun.ttc”或“simhei.ttf”)。
运行代码后,会显示生成的词云图窗口。
原文地址: http://www.cveoy.top/t/topic/qtDt 著作权归作者所有。请勿转载和采集!