答:
import os
# 文件路径
file_path = os.path.join("data", "data22462", "成绩单.txt")
# 读入文件
with open(file_path, "r", encoding="utf-8") as f:
lines = f.readlines()
# 学生总分字典
total_scores = {}
# 循环处理每个学生
for line in lines:
line = line.strip()
if not line: # 忽略空行
continue
student_data = line.split("\t")
student_name = student_data[0]
scores = list(map(int, student_data[1:])) # 将成绩从字符串转换为整数
total_score = sum(scores) # 计算总分
total_scores[student_name] = total_score # 添加到总分字典中
# 学生总分列表,每个元素是一个元组,包括学生姓名和总分
total_scores_list = list(total_scores.items())
# 按照总分排序
total_scores_list.sort(key=lambda x: x[1], reverse=True)
# 计算排名
rank = 1
last_score = None
for i, (name, score) in enumerate(total_scores_list):
if last_score is None or last_score != score:
rank = i + 1
if last_score is not None and last_score == score:
total_scores_list[i - 1] = (total_scores_list[i - 1][0], total_scores_list[i - 1][1], "并列排名:" + str(rank))
rank += 1
total_scores_list[i] = (name, score, "排名:" + str(rank))
last_score = score
# 将结果写入文件
output_file_path = os.path.join("work", "总成绩排名.txt")
with open(output_file_path, "w", encoding="utf-8") as f:
for name, score, rank_str in total_scores_list:
f.write(name + "\t总分:" + str(score) + "\t" + rank_str + "\n")
# 查询程序
while True:
name = input("请输入学生姓名(直接回车退出):")
if not name:
break
for nm, sc, rk in total_scores_list:
if nm == name:
print("{} 总分:{} {}".format(name, sc, rk))
break
else:
print("找不到名叫 {} 的学生".format(name))