我已经从ESPN的API中创建了一个字典,其中包含了我需要的一堆数据,并且它都很整洁和有组织。我需要。csv格式的数据给我的朋友做机器学习,但是我不知道从哪里开始。
下面是我的代码,将来自API的数据格式化为dict data
注意:我有打印(数据)在底部,这是临时的,并帮助谁运行它。
import requests
root_link = "http://sports.core.api.espn.com/v2/sports/football/leagues/nfl/seasons/2022/types/2/weeks?lang=en®ion=us"
response1 = requests.get(url=root_link)
weeks = response1.json()
data = {}
for i in range(16):
print(f"========= WEEK {i + 1}/16 =========")
week_link = weeks["items"][i]["$ref"]
response2 = requests.get(url=week_link)
week_data = response2.json()
get_events = week_data["events"]["$ref"]
response3 = requests.get(url=get_events)
week_games = response3.json()
week_data_for_dict = {}
for j in range(len(week_games["items"])):
game_link = week_games["items"][j]["$ref"]
response4 = requests.get(url=game_link)
game = response4.json()
event_name = game["name"]
event_date = game["date"]
event_short_name = ["shortName"]
if game["competitions"][0]["competitors"][0]["winner"]:
winner_link = game["competitions"][0]["competitors"][0]["team"]["$ref"]
else:
winner_link = game["competitions"][0]["competitors"][1]["team"]["$ref"]
response5 = requests.get(url=winner_link)
winner_data = response5.json()
winner = winner_data["displayName"]
week_data_for_dict[f"Game {j + 1}"] = {
"Event Name": event_name,
"Short Name": event_short_name,
"Date": event_date,
"Winner": winner
}
print(f"FINISHED FOR GAME {j + 1}/{len(week_games['items'])}")
data[f"Week {i + 1}"] = week_data_for_dict
print(data)
我想使用pandas,因为我听说这是最简单的方法,但如果有更简单的方法,请告诉我。
首先安装pandas,在您的Windows powershell或终端中写入命令:
pip install pandas
要使用pandas,并将您的字典转换为csv格式,您应该使用:
import pandas as pd
df = pd.DataFrame(output)
df.to_csv('espn.csv')
print('okay')
我希望它能成功。