
本文档旨在提供一个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()用于移除行首尾的空白字符,避免干扰数据解析。如果某行数据不完整(不是三个字段),会打印警告信息。
注意事项:
立即学习“Python免费学习笔记(深入)”;
接下来,我们需要根据平时成绩和期末成绩计算综合成绩,并将学号和综合成绩写入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免费学习笔记(深入)”;
最后,我们需要统计各分数段的学生人数,并计算班级平均分。分数段的划分标准为:
# 统计各分数段人数
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免费学习笔记(深入)”;
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处理学生成绩:从文件读取到统计分析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号