读取CSV文件提取英超赛事指定数据的实现问题(禁止使用pandas)
英超赛事CSV数据处理实现方案
原代码问题梳理
- 文件操作逻辑错误:
f.close()和return放在了for循环内部,导致只遍历第一行数据就直接返回结果,无法读取全部赛事数据 - 没有接收球队名称输入参数,也没有区分主客场进球的归属,当前逻辑是统计所有赛事的总进球,而非指定球队的进球数
- 缺少赛事编号查询对阵信息的功能实现
- 没有异常处理逻辑,无法兼容文件不存在、输入内容不合法等边界场景
调整后完整实现代码
def count_team_total_goals(team_name: str, file_path: str = "EPL_18-19_HW2.txt") -> int: """统计指定球队的赛季总进球数""" total_goals = 0 try: # 用with上下文自动管理文件关闭,避免手动关闭出错 with open(file_path, 'r', encoding='utf-8') as f: next(f) # 跳过表头行 for line in f: line = line.strip() if not line: # 跳过空行 continue fields = line.split(',') # 字段索引对应:0=赛事编号、2=主队名称、3=全场比分、5=客队名称 home_team = fields[2] away_team = fields[5] ft_goals = fields[3].split('-') home_goals = int(ft_goals[0]) away_goals = int(ft_goals[1]) # 对应球队累加对应主场/客场进球 if team_name == home_team: total_goals += home_goals elif team_name == away_team: total_goals += away_goals return total_goals except FileNotFoundError: print(f"错误:未找到数据文件{file_path}") return -1 def get_game_by_id(game_id: int, file_path: str = "EPL_18-19_HW2.txt") -> dict | None: """根据赛事编号查询对阵信息,查询不到返回None""" try: with open(file_path, 'r', encoding='utf-8') as f: next(f) for line in f: line = line.strip() if not line: continue fields = line.split(',') current_game_id = int(fields[0]) if current_game_id == game_id: return { "home_team": fields[2], "away_team": fields[5], "full_time_score": fields[3] } return None except FileNotFoundError: print(f"错误:未找到数据文件{file_path}") return None if __name__ == "__main__": # 交互菜单 while True: print("\n功能菜单:") print("1. 查询指定球队赛季总进球数") print("2. 查询指定赛事的对阵信息") print("3. 退出程序") choice = input("请输入功能编号:") if choice == '1': team = input("请输入要查询的球队完整名称:") goals = count_team_total_goals(team) if goals == -1: continue print(f"{team} 赛季总进球数为:{goals}") elif choice == '2': try: g_id = int(input("请输入要查询的赛事编号:")) except ValueError: print("错误:赛事编号必须为数字") continue game_info = get_game_by_id(g_id) if not game_info: print("未找到对应赛事信息") continue print(f"赛事编号{g_id}对阵信息:{game_info['home_team']} {game_info['full_time_score']} {game_info['away_team']}") elif choice == '3': break else: print("请输入正确的功能编号")
注意事项
- 要求CSV数据文件的字段顺序和你提供的样例完全一致,字段分隔符为英文逗号
- 输入球队名称时需要和数据中的名称完全匹配,区分大小写、空格和特殊字符
内容的提问来源于stack exchange,提问作者joeyfroots
相关产品推荐
相关产品推荐

