使用 Python 中的字典从 Hockey API 中抓取数据

我开始从事一个有趣的项目,以更好地练习我的数据抓取技能,我从 NHL API 抓取数据并尝试记录射门和进球的所有位置坐标(此 API 将向您显示任何 NHL 比赛并具有坐标以及在所述游戏中发生的每个事件的玩家信息)。但是,我在通过数据编制索引时遇到问题,而且我真的不确定如何处理它。下面是我的代码...


import requests as rq

import csv


GAME_ID = "2017021121" #Game ID indicates which game I want to look at...first 4 digits is the year, second two the point in season, (01 Pre, 02 Reg, 03 Playoffs, 04 All Star)


#URL to access the coordinates of every event in given game...comes in nested dictionary form

url = f"https://statsapi.web.nhl.com/api/v1/game/{GAME_ID}/feed/live"

game = rq.get(url)

#turn the file into a readable one

contents = game.text


#split text into list so we can fool around with it

contents_list = list(csv.reader(contents.splitlines()))


def main():

    file = open( f'coordinates.{GAME_ID}.txt', 'a')

我现在要做的是使用 for 循环遍历数据集并检查“事件类型”以及它们是否等于“射门”或“目标”,以及它们是否要添加它们的值x, y 坐标到打印到新文件中的字典。我已经尝试通过自己建立索引,但我不太擅长数据抓取,所以我没有走得太远。作为参考,这里是数据集的样子(或至少是它的一个片段)。

} ],

        "result" : {

          "event" : "Penalty",

          "eventCode" : "COL162",

          "eventTypeId" : "PENALTY",

          "description" : "Blake Coleman Tripping against Erik Johnson",

          "secondaryType" : "Tripping",

          "penaltySeverity" : "Minor",

          "penaltyMinutes" : 2

        },

        "about" : {

          "eventIdx" : 30,

          "eventId" : 162,

          "period" : 1,

          "periodType" : "REGULAR",

          "ordinalNum" : "1st",

          "periodTime" : "04:47",

          "periodTimeRemaining" : "15:13",

          "dateTime" : "2019-03-17T19:15:33Z",

          "goals" : {

            "away" : 0,

            "home" : 0

          }

        },

        "coordinates" : {

          "x" : -58.0,

          "y" : -37.0

        },



对我来说,它看起来像是一堆嵌套的字典,但我又不太确定。


任何帮助将不胜感激!!谢谢你!!


RISEBY
浏览 80回答 2
2回答

慕仙森

它看起来像一个大列表,包含字典列表。您可以使用for-each-loop.for entry in list:然后,您可以单独查看每个条目并检查它们是否eventTypeId等于shot或goal:if entry["result"]["eventTypeId"] == "SHOT":在这种情况下,您可以像这样提取 X 和 Y 坐标的值:x = entry["coordinates"]["x"] y = entry["coordinates"]["y"]之后,您可以使用这些坐标来做任何您想做的事情。

慕的地8271018

您可以遍历列表,通过将所需数据放入字典中以使用 pandas 构建表。import requests as rqimport pandas as pdGAME_ID = "2017021121" #Game ID indicates which game I want to look at...first 4 digits is the year, second two the point in season, (01 Pre, 02 Reg, 03 Playoffs, 04 All Star)#URL to access the coordinates of every event in given game...comes in nested dictionary formurl = f"https://statsapi.web.nhl.com/api/v1/game/{GAME_ID}/feed/live"game = rq.get(url).json()game = game['liveData']['plays']['allPlays']rows = []for each in game:    if each['result']['event'] in ['Shot','Goal']:        print(each['result']['event'])        row = {                'result':each['result']['event'],                'x':each['coordinates']['x'],                'y':each['coordinates']['y']}        rows.append(row)        df = pd.DataFrame(rows)输出:print(df)   result     x     y0    Shot  76.0  -8.01    Shot -41.0 -24.02    Shot  69.0  -1.03    Shot  37.0  30.04    Shot -60.0   1.05    Goal  43.0 -20.06    Shot -85.0   6.07    Shot -83.0  11.08    Shot -85.0  -5.09    Shot  81.0  -1.010   Shot -84.0  -7.011   Shot -81.0  -3.012   Shot -57.0  12.013   Shot  74.0 -14.014   Goal  64.0   0.015   Shot  68.0   2.016   Shot  73.0   5.017   Shot  63.0  -2.018   Shot -26.0 -16.019   Shot -84.0  -2.020   Shot -74.0  36.021   Shot  83.0   6.022   Shot -88.0   7.023   Shot -39.0  30.024   Shot -69.0 -22.025   Shot  65.0  32.026   Shot  80.0  -3.027   Shot -70.0  -6.028   Shot -87.0  17.029   Shot -29.0 -20.0..    ...   ...   ...47   Shot  81.0   1.048   Shot -82.0   0.049   Shot  38.0 -28.050   Shot  66.0  -9.051   Shot  49.0   5.052   Shot -48.0 -12.053   Shot  39.0  20.054   Goal  75.0  -9.055   Shot -84.0  -7.056   Shot  88.0 -28.057   Shot  41.0 -20.058   Shot -41.0  12.059   Shot  40.0   7.060   Shot  72.0  -4.061   Goal  86.0   7.062   Shot -77.0  -8.063   Shot  34.0 -32.064   Shot -79.0 -10.065   Shot  61.0   6.066   Shot -43.0  17.067   Shot -41.0  -5.068   Shot -35.0  19.069   Shot -45.0 -11.070   Shot -77.0  -8.071   Shot  80.0  -1.072   Shot -87.0   7.073   Shot  84.0  24.074   Shot  76.0   7.075   Goal  83.0 -18.076   Shot -81.0  -5.0[77 rows x 3 columns]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python