Python3.9分步开发:基于JSON/TXT生成运动员成绩排名表
Python 3.9 运动员成绩排名程序实现分步指导
步骤1:读取运动员基础信息(JSON文件)
用Python内置的json模块读取file.json,以胸牌号为键存储运动员的姓名与姓氏。注意JSON中胸牌号是字符串类型,需与后续结果文件中的胸牌号匹配。
代码示例:
import json from datetime import datetime # 读取运动员信息 athlete_info = {} with open('file.json', 'r', encoding='utf-8') as f: athlete_info = json.load(f)
步骤2:解析比赛时间记录(TXT文件)
逐行读取result.txt,提取每个运动员的起始(start)、结束(finish)时间并转为datetime对象,方便后续计算时间差。用字典存储每个胸牌号对应的完整时间记录。
代码示例:
athlete_times = {} with open('result.txt', 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line: continue # 分割行内容:胸牌号、时间类型、时间字符串(maxsplit=2避免拆分时间里的冒号) chest_num, time_type, time_str = line.split(maxsplit=2) # 转换时间字符串为datetime对象(适配带逗号的微秒格式) time_obj = datetime.strptime(time_str, '%H:%M:%S,%f') # 初始化字典条目 if chest_num not in athlete_times: athlete_times[chest_num] = {} athlete_times[chest_num][time_type] = time_obj
步骤3:计算有效运动员的成绩
遍历时间字典,仅保留同时拥有start和finish记录的运动员,计算时间差并关联对应的姓名信息。
代码示例:
athlete_results = [] for chest_num, times in athlete_times.items(): # 跳过时间记录不完整的运动员 if 'start' not in times or 'finish' not in times: continue # 计算成绩时间差 result_delta = times['finish'] - times['start'] # 匹配姓名信息(无信息时显示Unknown) if chest_num in athlete_info: first_name = athlete_info[chest_num]['Surname'] last_name = athlete_info[chest_num]['Name'] else: first_name = 'Unknown' last_name = 'Unknown' # 存储结果数据 athlete_results.append({ 'chest_num': chest_num, 'first_name': first_name, 'last_name': last_name, 'result': result_delta })
步骤4:按成绩排序生成排名
将运动员结果按成绩(时间差从小到大)排序,成绩越短排名越靠前。
代码示例:
# 按成绩升序排序 athlete_results_sorted = sorted(athlete_results, key=lambda x: x['result'])
步骤5:格式化输出排名表
按照指定格式输出排名,确保列对齐,并将timedelta对象转为MM:SS,xx的格式(分钟:秒,两位小数秒部分)。
代码示例:
# 打印表头 print(f"{'Occupied place':>12}|{'Chest number':>13}|{'First Name':>10}|{'Last Name':>11}|{'Result':>8}") # 遍历排序后的结果输出每行 for idx, athlete in enumerate(athlete_results_sorted, start=1): total_seconds = athlete['result'].total_seconds() minutes = int(total_seconds // 60) seconds = total_seconds % 60 # 转换为指定格式,替换小数点为逗号 result_str = f"{minutes:02d}:{seconds:05.2f}".replace('.', ',') # 格式化每行内容,保证列对齐 print(f"{idx:>12} |{athlete['chest_num']:>12} |{athlete['first_name']:>10} |{athlete['last_name']:>11} |{result_str:>8}")
完整整合脚本
将上述步骤整合为完整脚本,增加文件缺失的异常处理:
import json from datetime import datetime def main(): # 读取运动员信息 athlete_info = {} try: with open('file.json', 'r', encoding='utf-8') as f: athlete_info = json.load(f) except FileNotFoundError: print("错误:未找到file.json文件") return # 解析时间记录 athlete_times = {} try: with open('result.txt', 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line: continue chest_num, time_type, time_str = line.split(maxsplit=2) time_obj = datetime.strptime(time_str, '%H:%M:%S,%f') if chest_num not in athlete_times: athlete_times[chest_num] = {} athlete_times[chest_num][time_type] = time_obj except FileNotFoundError: print("错误:未找到result.txt文件") return # 计算成绩 athlete_results = [] for chest_num, times in athlete_times.items(): if 'start' not in times or 'finish' not in times: continue result_delta = times['finish'] - times['start'] if chest_num in athlete_info: first_name = athlete_info[chest_num]['Surname'] last_name = athlete_info[chest_num]['Name'] else: first_name = 'Unknown' last_name = 'Unknown' athlete_results.append({ 'chest_num': chest_num, 'first_name': first_name, 'last_name': last_name, 'result': result_delta }) # 排序 athlete_results_sorted = sorted(athlete_results, key=lambda x: x['result']) # 输出排名表 print(f"{'Occupied place':>12}|{'Chest number':>13}|{'First Name':>10}|{'Last Name':>11}|{'Result':>8}") for idx, athlete in enumerate(athlete_results_sorted, start=1): total_seconds = athlete['result'].total_seconds() minutes = int(total_seconds // 60) seconds = total_seconds % 60 result_str = f"{minutes:02d}:{seconds:05.2f}".replace('.', ',') print(f"{idx:>12} |{athlete['chest_num']:>12} |{athlete['first_name']:>10} |{athlete['last_name']:>11} |{result_str:>8}") if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者ne_vladi
相关产品推荐
相关产品推荐

