如何让Python开发的NHL赛事查询程序仅展示指定选中球队的胜负结果
解决方案
修改说明
- 新增可自定义的关注球队列表,直接修改列表内的球队名称即可调整要展示的队伍
- 调整原逻辑仅输出关注球队的胜负状态,匹配你给出的示例输出格式
- 修复原代码缺失右括号的语法问题,同时优化异常处理逻辑,避免请求失败时报变量未定义的错误
完整实现代码
import requests from requests.exceptions import HTTPError # 在这里填写你要关注的球队名称,可自行增减 follow_teams = ["Carolina Hurricanes", "Toronto Maple Leafs"] ids = [] try: response = requests.get( 'https://statsapi.web.nhl.com/api/v1/schedule?expand=schedule.teams,schedule.linescore') response.raise_for_status() jsonResponse = response.json() games = jsonResponse["dates"][0]['games'] for i in games: ids.append(i['gamePk']) except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other error occurred: {err}') def game_compare(n): url = "https://statsapi.web.nhl.com/api/v1/game/" + str(n) + "/feed/live" try: response = requests.get(url) response.raise_for_status() jsonResponse = response.json() home = jsonResponse["liveData"]['linescore']['teams']['home']['team']['name'] goals_home = jsonResponse["liveData"]['linescore']['teams']['home']['goals'] away = jsonResponse["liveData"]['linescore']['teams']['away']['team']['name'] goals_away = jsonResponse["liveData"]['linescore']['teams']['away']['goals'] # 仅处理关注的球队 if home in follow_teams: if goals_home > goals_away: print(f"{home}: Winning") elif goals_home < goals_away: print(f"{home}: Losing") else: print(f"{home}: Tied") if away in follow_teams: if goals_away > goals_home: print(f"{away}: Winning") elif goals_away < goals_home: print(f"{away}: Losing") else: print(f"{away}: Tied") except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other error occurred: {err}') for i in ids: game_compare(i)
效果说明
运行后会自动筛选当日所有涉及你指定球队的比赛,输出对应球队的胜负状态,和你给出的示例输出格式完全一致。如果你需要保留领先分差信息,只需要修改print语句的内容,补充分差计算逻辑即可。
内容的提问来源于stack exchange,提问作者AlexLikesWater
相关产品推荐
相关产品推荐

