
本文旨在指导读者如何使用Python处理包含学生学号、平时成绩和期末成绩的文本文件,计算每个学生的总评成绩,并将结果写入新文件。同时,统计各分数段人数,并计算全班平均分。通过本文,读者将掌握文件读写、数据处理、循环控制和统计计算等常用Python编程技巧。
问题分析与改进
原始代码存在的主要问题是:
改进后的代码
立即学习“Python免费学习笔记(深入)”;
以下是改进后的Python代码,解决了上述问题,并实现了完整的功能:
import re
def process_student_scores(input_file, output_file):
"""
处理学生成绩数据,计算总评成绩,统计分数段,并计算平均分。
Args:
input_file (str): 输入文件路径,包含学生学号、平时成绩和期末成绩,以空格分隔。
output_file (str): 输出文件路径,保存学生学号和总评成绩。
"""
student_scores = []
total_score = 0
grade_counts = {'90+': 0, '80-89': 0, '70-79': 0, '60-69': 0, '<60': 0}
try:
with open(input_file, 'r') as f:
for line in f:
# 使用正则表达式分割字符串
data = re.split(r'\s+', line.strip())
if len(data) != 3:
print(f"Warning: Invalid data format in line: {line.strip()}")
continue
student_id, usual_score, final_score = data
try:
usual_score = int(usual_score)
final_score = int(final_score)
except ValueError:
print(f"Warning: Invalid score format in line: {line.strip()}")
continue
overall_score = round(0.4 * usual_score + 0.6 * final_score)
student_scores.append((student_id, overall_score))
total_score += overall_score
# 统计分数段
if overall_score >= 90:
grade_counts['90+'] += 1
elif 80 <= overall_score <= 89:
grade_counts['80-89'] += 1
elif 70 <= overall_score <= 79:
grade_counts['70-79'] += 1
elif 60 <= overall_score <= 69:
grade_counts['60-69'] += 1
else:
grade_counts['<60'] += 1
# 写入结果到文件
with open(output_file, 'w') as f:
for student_id, overall_score in student_scores:
f.write(f"{student_id} {overall_score}\n")
# 计算平均分
num_students = len(student_scores)
average_score = total_score / num_students if num_students > 0 else 0
# 输出统计结果
print(f"Total number of students: {num_students}")
print("Grade distribution:")
for grade, count in grade_counts.items():
print(f"{grade}: {count}")
print(f"Average score: {average_score:.1f}")
except FileNotFoundError:
print(f"Error: Input file '{input_file}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# 示例用法
input_file = "score1.txt"
output_file = "score2.txt"
process_student_scores(input_file, output_file)代码解释
注意事项
总结
本文提供了一个使用Python处理学生成绩数据的完整示例,涵盖了文件读写、数据处理、循环控制、统计计算和错误处理等常用编程技巧。通过学习本文,读者可以掌握如何使用Python处理类似的数据处理任务,并根据实际需求进行修改和扩展。记住要仔细检查输入数据的格式,并进行适当的错误处理,以确保程序的稳定性和可靠性。
以上就是Python处理学生成绩数据:计算总评、统计分数段及计算平均分的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号