import jieba
import matplotlib.pyplot as plt

file = open('pingjia.txt', 'r', encoding='utf-8')
txt = file.read()
words = jieba.lcut(txt)
count = {}

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()

代码功能:

  1. 读取用户评价文本:pingjia.txt 文件中读取用户评价文本。
  2. 使用 Jieba 库进行分词: 使用 jieba.lcut(txt) 对文本进行分词,得到所有词语列表。
  3. 统计词频: 遍历分词结果,统计每个词语出现的次数,并将结果存储在 count 字典中。
  4. 排除无关词语: 定义一个 exclude 列表,包含需要排除的无关词语,并在 count 字典中删除这些词语。
  5. 排序并选取高频词:count 字典中的词语按照词频从高到低排序,并选取前 10 个高频词。
  6. 绘制柱状图: 使用 Matplotlib 库绘制前 10 个高频词的柱状图,横轴为词语,纵轴为词频。

代码优点:

  • 使用 Jieba 库进行中文分词,方便处理中文文本。
  • 使用 Matplotlib 库绘制柱状图,直观地展示分析结果。
  • 排除无关词语,提高分析结果的准确性。
  • 代码简洁易懂,易于理解和修改。

使用说明:

  1. 将用户评价文本保存为 pingjia.txt 文件。
  2. 运行代码,即可生成用户评价词频柱状图。

注意:

  • 确保已安装 Jieba 和 Matplotlib 库。
  • exclude 列表中的词语可以根据实际情况进行调整。
  • 可以调整代码中的参数,例如 top_words 的取值,来改变柱状图中显示的词语数量。
Python 使用 Jieba 分词与 Matplotlib 绘制用户评价词频柱状图

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

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