0

0

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

DDD

DDD

发布时间:2025-07-15 17:22:02

|

452人浏览过

|

来源于php中文网

原创

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

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

文件读取与数据解析

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

import re

def 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()用于移除行首尾的空白字符,避免干扰数据解析。如果某行数据不完整(不是三个字段),会打印警告信息。

注意事项:

Red Panda AI
Red Panda AI

AI文本生成图像

下载

立即学习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,
        "<60": 0
    }

    total_score = 0
    num_students = len(student_results)

    for score in student_results.values():
        total_score += score
        if score >= 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["<60"] += 1

    # 计算平均分
    average_score = total_score / num_students if num_students > 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 re

def 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,
        "<60": 0
    }

    total_score = 0
    num_students = len(student_results)

    for score in student_results.values():
        total_score += score
        if score >= 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["<60"] += 1

    # 计算平均分
    average_score = total_score / num_students if num_students > 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开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

715

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

625

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

739

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

617

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1235

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

547

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

575

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

698

2023.08.11

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.6万人学习

Django 教程
Django 教程

共28课时 | 2.6万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.0万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号