Python文本分析:用户评价词频图可视化

本代码示例使用Python的结巴分词库对用户评价文本进行分析,并利用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]

# 获取词频前10的词语
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()

代码运行结果:

该代码会生成一个柱状图,展示用户评价文本中出现频率最高的10个词语。根据结果,'好'是用户评价中出现最频繁的词语,其次是'不错'和'喜欢'。

代码说明:

  • jieba.lcut(txt):使用结巴分词库对文本进行分词。
  • count.get(word, 0) + 1:统计每个词语出现的次数。
  • exclude:定义需要移除的无关词语。
  • sorted(count.items(), key=lambda x: x[1], reverse=True):对词频进行排序,并选取前10个词语。
  • plt.rcParams['font.sans-serif'] = ['SimHei']:设置matplotlib库的字体为SimHei,用于显示中文。
  • plt.bar(x, y):绘制柱状图。

注意事项:

  • 需要安装结巴分词库和matplotlib库。
  • pingjia.txt文件需要包含用户评价文本。
  • 可以根据需要修改代码中 exclude 列表,添加或删除需要移除的无关词语。
Python文本分析:利用结巴分词和matplotlib绘制用户评价词频图

原文地址: https://www.cveoy.top/t/topic/n0f6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录