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
# 增加删词列表
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] # 取出频率前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()
代码说明:
- 导入库:
import jieba和import matplotlib.pyplot as plt分别导入Jieba库和matplotlib库。 - 读取文件:
file = open('pingjia.txt', 'r', encoding='utf-8')打开名为pingjia.txt的文件,并使用file.read()读取文件内容。 - 分词:
words = jieba.lcut(txt)使用Jieba库对文本进行分词。 - 词频统计: 使用
count字典统计每个词出现的次数。 - 删除停用词: 定义一个
exclude列表,包含常见的停用词,并使用循环从count字典中删除这些停用词。 - 排序并取前10: 使用
sorted对count字典进行排序,并使用切片[:10]获取词频最高的10个词。 - 绘制柱状图: 使用matplotlib库绘制词频柱状图。
注意: pingjia.txt文件需要在代码所在的目录下。
本文展示了一个简单的文本分析示例,你可以根据自己的需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/n0gc 著作权归作者所有。请勿转载和采集!