Python对学生成绩TXT文本数据分析

题目:

从文本文件逐行读入某个班级的百分制成绩序列,计算基本统计值(最大值、最小值、平均值、标准差、中位数),并统计成绩在不同区间([0, 59]、[60,69]、[70,79]、[80,89]、[90,100])的累计数量和百分比。除累计数量外,其他输出保留小数点后两位。并将统计结果存入文本文件中

思路:

主要考察了对python读取文件和写入文件的使用方法

代码:

stu = []


def get_file(file_path):
    fo = open(file_path, "r")
    while True:
        line = fo.readline()
        if len(line) == 0:
            break
        stu.append(float(line.strip('\n')))


def calculate(file_path):
    fo = open(file_path, "a+")
    stu.sort()
    fo.write("\n")
    fo.write("最小值:{}\n".format(round(stu[0]), 2))
    stu.sort(reverse=True)
    fo.write("最大值:{}\n".format(round(stu[0]), 2))
    avg = sum(stu)/len(stu)
    fo.write("平均值:{}\n".format(round(avg, 2)))
    # 计算标准差
    s = 0
    for i in stu:
        s = s + (i-avg)*(i-avg)
    s = s / len(stu)
    s = pow(s, 0.5)
    fo.write("标准差:{}\n".format(round(s, 2)))
    # 计算中位数
    stu.sort()
    med = stu[len(stu) // 2]
    if len(stu) % 2 == 0:
        med = (med + stu[(len(stu)//2) + 1]) / 2
    fo.write("中位数:{}\n".format(round(med, 2)))

    # 计算分数段占比
    count = [0, 0, 0, 0, 0]
    for i in stu:
        if i < 60:
            count[0] += 1
        elif i < 70:
            count[1] += 1
        elif i < 80:
            count[2] += 1
        elif i < 90:
            count[3] += 1
        elif i < 100:
            count[4] += 1
    fo.write("[0, 59]累计数量{},百分比{}\n".format(count[0], round(count[0]/len(stu), 2)))
    fo.write("[60, 69]累计数量{},百分比{}\n".format(count[1], round(count[1] / len(stu), 2)))
    fo.write("[70, 79]累计数量{},百分比{}\n".format(count[2], round(count[2] / len(stu), 2)))
    fo.write("[80, 89]累计数量{},百分比{}\n".format(count[3], round(count[3] / len(stu), 2)))
    fo.write("[90, 100]累计数量{},百分比{}\n".format(count[4], round(count[4] / len(stu), 2)))
    fo.close()
    print("Done")

file_path = input("请输入文件地址:")
get_file(file_path)
calculate(file_path)

效果:

请添加图片描述

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值