python实现词语统计并柱状图显示

(1)实现一篇文档的读入功能;

(2)筛选出文档中出现重复的字的词频数量;

(3)用柱状图显示重复的字出现次数前十的数据;

(4)包括简单的异常处理功能;

(5)要求功能完整,无明显逻辑语法错误;

主要用到python的两个工具包(1)jieba分词库 (2)matplotlib -绘图领域使用最广泛的套件

实现代码

import jieba#引入jieba分词库
import matplotlib.pyplot as plt

try:
    txt = open("Test_data.txt", "r", encoding="utf-8").read()#打开文本
except Exception as ex:
    print("出错了,请联系管理员!")
    print(ex)# 
words = jieba.lcut(txt)#进行分词处理并形成列表
counts = {}#构造字典,逐一遍历words中的中文单词进行处理,并用字典计数
for word in words:
    if len(word) == 1:
        continue
    else:
        counts[word] = counts.get(word, 0) + 1
items = list(counts.items())#转换列表类型并排序
items.sort(key=lambda x:x[1], reverse=True)

newitems = items[0:10:1]
# 转换成字典
tu = dict(newitems)
# 定义 x和 y的空列表,用于分别存放tu字典的键和值
x = []
y = []
# 列车键和分别追加到x和y列表
for k in tu:
    x.append(k)
    y.append(tu[k])
# 打印标题
plt.title('word access')
# 打印x标签
plt.xlabel('The number of times a word appeared')
# 打印y标签
plt.ylabel('increase')
plt.xticks(rotation=0)
# 输出图表中间的文字各种格式的定义
for a, b in zip(x, y):
    plt.text(a, b, '%.0f' % b, ha='center', va='bottom', fontsize=12,)
# 以柱状形式打印图表,并打印标签名,还有其他图表格式的如饼图等,需要的text格式不同
plt.bar(x, y, label='number')
plt.legend()
# 图表展示
plt.show()
for i in range(10):#输出前10位单词
    word, count = items[i]
    print("{0:<10}{1:<5}".format(word, count))

在同级目录下建立 Test_data.txt 文档

在编写过程用遇到问题

1.python导入jieba(换行即为enter)

win + R 
cmd
pip install jieba

2.python导入matplotlib

win + R
cmd
python -m pip install matplotlib

3.matplotlib 中文乱码问题

Matplotlib中文乱码解决方案(两种方式) (biancheng.net)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值