Python 使用 Jieba 库进行文本分析,并绘制词频统计图
Python 使用 Jieba 库进行文本分析,并绘制词频统计图
本文将介绍如何使用 Python 的 Jieba 库对文本进行分词,并通过 matplotlib 绘制词频统计图。
import jieba
import matplotlib.pyplot as plt
file = open('pingjia.txt', 'r', encoding='utf-8')
txt = file.read()
words = jieba.lcut(txt)
count = {}
# 在分词前修改停用词表
jieba.del_word(',')
jieba.del_word(':')
jieba.del_word('!')
for word in words:
if len(word) < 1:
continue
else:
count[word] = count.get(word, 0) + 1
# 添加自定义词语
jieba.add_word('非常喜欢')
jieba.add_word('物流给力')
jieba.add_word('桃子新鲜')
# 移除其他停用词
jieba.del_word('!')
jieba.del_word('的')
jieba.del_word(':')
jieba.del_word(',')
exclude = ['可以', '的', '。', ':', '', '!']
for key in list(count.keys()):
if key in exclude:
del count[key]
top_words = sorted(count.items(), key=lambda x: x[1], reverse=True)[:10]
x = [word[0] for word in top_words]
y = [word[1] for word in top_words]
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.title('用户评价分析')
plt.xlabel('评价')
plt.ylabel('数量')
plt.bar(x, y)
plt.show()
问题:为什么 jieba.del_word 不起作用?
通常,在运行 jieba.del_word 之前已经完成了文本分词,所以对停用词表的更改不会影响已经分好的词语。
解决方法:
- 在分词前修改停用词表: 将
jieba.del_word放在jieba.lcut之前。 - 在分词函数中添加停用词参数:
jieba.lcut函数支持stop_words参数,可以在分词时直接排除指定的停用词。
通过以上方法,您可以有效地使用 jieba.del_word 删除停用词,并进行准确的词频统计。
希望本文能够帮助您更好地理解 Jieba 库的使用,并进行文本分析和可视化。
原文地址: https://www.cveoy.top/t/topic/n0gp 著作权归作者所有。请勿转载和采集!