Python处理学生成绩:从文件读取到统计分析

python处理学生成绩:从文件读取到统计分析

本文档旨在提供一个Python程序,用于读取包含学生成绩信息的文本文件,计算综合成绩,并将结果写入新文件。同时,程序还将统计各分数段的学生人数,并计算班级平均分。通过本文,你将学习如何使用Python进行文件读写、数据处理和统计分析。

文件读取与数据解析

首先,我们需要从score1.txt文件中读取数据。文件中的每一行包含学生的学号、平时成绩和期末成绩,数据之间用空格分隔。以下代码展示了如何读取文件并解析数据:

import redef process_scores(input_file="score1.txt", output_file="score2.txt"):    """    读取学生成绩文件,计算综合成绩,并输出到新文件,同时进行统计分析。    """    student_scores = []    try:        with open(input_file, 'r') as f:            for line in f:                # 使用正则表达式分割字符串,处理多个空格的情况                data = re.split(r's+', line.strip())                if len(data) == 3:  # 确保每行数据完整                    student_scores.append(data)                else:                    print(f"Warning: Invalid data line: {line.strip()}")    except FileNotFoundError:        print(f"Error: Input file '{input_file}' not found.")        return    # 打印读取的数据,方便调试    print("Raw data read from file:", student_scores)

上述代码使用with open()语句打开文件,确保文件在使用完毕后自动关闭。re.split(r’s+’, line.strip()) 使用正则表达式s+来分割字符串,可以处理多个空格的情况,line.strip()用于移除行首尾的空白字符,避免干扰数据解析。如果某行数据不完整(不是三个字段),会打印警告信息。

注意事项:

立即学习“Python免费学习笔记(深入)”;

确保score1.txt文件存在,并且格式正确。使用re.split()可以更灵活地处理数据之间的分隔符。增加错误处理机制,例如try…except块,可以提高程序的健壮性。

综合成绩计算与文件写入

接下来,我们需要根据平时成绩和期末成绩计算综合成绩,并将学号和综合成绩写入score2.txt文件。综合成绩的计算公式为:综合成绩 = 平时成绩 * 0.4 + 期末成绩 * 0.6。

    # 计算综合成绩并写入新文件    student_results = {}    with open(output_file, 'w') as p:        for student in student_scores:            student_id, usual_score, final_score = student            try:                usual_score = int(usual_score)                final_score = int(final_score)                score = round(0.4 * usual_score + 0.6 * final_score)                student_results[student_id] = score                p.write(f"{student_id} {score}n")            except ValueError:                print(f"Warning: Invalid score data for student {student_id}. Skipping.")    print("Calculated scores and wrote to file:", student_results)

这段代码遍历student_scores列表,计算每个学生的综合成绩,并将学号和综合成绩写入score2.txt文件。使用round()函数对综合成绩进行四舍五入。同时,增加了try…except块来处理成绩数据可能存在的ValueError异常。

注意事项:

立即学习“Python免费学习笔记(深入)”;

确保平时成绩和期末成绩可以转换为整数。使用f-string可以方便地格式化输出字符串。p.write(f”{student_id} {score}n”) 在每行末尾添加换行符n,确保每个学生的数据占据一行。

统计分析与结果输出

最后,我们需要统计各分数段的学生人数,并计算班级平均分。分数段的划分标准为:

90分及以上80-89分70-79分60-69分60分以下

    # 统计各分数段人数    grade_counts = {        "90+": 0,        "80-89": 0,        "70-79": 0,        "60-69": 0,        "= 90:            grade_counts["90+"] += 1        elif 80 <= score <= 89:            grade_counts["80-89"] += 1        elif 70 <= score <= 79:            grade_counts["70-79"] += 1        elif 60 <= score <= 69:            grade_counts["60-69"] += 1        else:            grade_counts[" 0 else 0    # 输出统计结果    print("Total number of students:", num_students)    print("Grade distribution:", grade_counts)    print("Average score: {:.1f}".format(average_score))# 调用函数进行处理process_scores()

这段代码首先定义了一个字典grade_counts来存储各分数段的学生人数。然后,遍历所有学生的综合成绩,统计各分数段的人数,并计算班级平均分。最后,将统计结果输出到控制台。

注意事项:

立即学习“Python免费学习笔记(深入)”;

使用字典可以方便地存储和访问各分数段的人数。”{:.1f}”.format(average_score) 用于格式化输出平均分,保留一位小数。if num_students > 0 else 0 用于处理没有学生的情况,避免除以零的错误。

完整代码

import redef process_scores(input_file="score1.txt", output_file="score2.txt"):    """    读取学生成绩文件,计算综合成绩,并输出到新文件,同时进行统计分析。    """    student_scores = []    try:        with open(input_file, 'r') as f:            for line in f:                # 使用正则表达式分割字符串,处理多个空格的情况                data = re.split(r's+', line.strip())                if len(data) == 3:  # 确保每行数据完整                    student_scores.append(data)                else:                    print(f"Warning: Invalid data line: {line.strip()}")    except FileNotFoundError:        print(f"Error: Input file '{input_file}' not found.")        return    # 打印读取的数据,方便调试    print("Raw data read from file:", student_scores)    # 计算综合成绩并写入新文件    student_results = {}    with open(output_file, 'w') as p:        for student in student_scores:            student_id, usual_score, final_score = student            try:                usual_score = int(usual_score)                final_score = int(final_score)                score = round(0.4 * usual_score + 0.6 * final_score)                student_results[student_id] = score                p.write(f"{student_id} {score}n")            except ValueError:                print(f"Warning: Invalid score data for student {student_id}. Skipping.")    print("Calculated scores and wrote to file:", student_results)    # 统计各分数段人数    grade_counts = {        "90+": 0,        "80-89": 0,        "70-79": 0,        "60-69": 0,        "= 90:            grade_counts["90+"] += 1        elif 80 <= score <= 89:            grade_counts["80-89"] += 1        elif 70 <= score <= 79:            grade_counts["70-79"] += 1        elif 60 <= score <= 69:            grade_counts["60-69"] += 1        else:            grade_counts[" 0 else 0    # 输出统计结果    print("Total number of students:", num_students)    print("Grade distribution:", grade_counts)    print("Average score: {:.1f}".format(average_score))# 调用函数进行处理process_scores()

总结

本文档详细介绍了如何使用Python处理学生成绩数据,包括文件读取、数据解析、综合成绩计算、文件写入、统计分析和结果输出。通过学习本文,你将掌握Python文件操作、数据处理和统计分析的基本技能。同时,本文还强调了错误处理的重要性,并提供了相应的代码示例。希望本文能够帮助你更好地理解和应用Python。

以上就是Python处理学生成绩:从文件读取到统计分析的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1364702.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月14日 04:10:13
下一篇 2025年12月14日 04:10:25

相关推荐

发表回复

登录后才能评论
关注微信