我有一个脚本,我试图抓住一个并不总是在那里的密钥的价值。我的IF声明存在问题。这是If Shotype is not None
我希望刮掉次要类型,这是一种射击,只有当射击发生时才会出现。
脚本:
import csv
import requests
import os
req = requests.get('https://statsapi.web.nhl.com/api/v1/game/2017010001/feed/live')
data = req.json()
my_data = []
pk = data['gameData']['game']['pk']
for item in data['liveData']['plays']['allPlays']:
players = item.get('players')
if players:
player_a = players[0]['player']['fullName'] if len(players) > 0 else None
player_b = players[1]['player']['fullName'] if len(players) > 1 else None
player_c = players[2]['player']['fullName'] if len(players) > 2 else None
player_d = players[3]['player']['fullName'] if len(players) > 3 else None
else:
player_a, player_b, player_c, player_d = None, None, None, None
if shotype is not None:
shotype = item['result']['secondaryType']
event = item['result']['event']
shotype = item['result']['secondaryType']
time = item['about']['periodTime']
Tm = item.get('team', {}).get('triCode')
coordinates_x, coordinates_y = item['coordinates'].get('x'), item['coordinates'].get('y')
my_data.append([pk, player_a, player_b, player_c, player_d, event, shotype, time, Tm, coordinates_x, coordinates_y])
headers = ["pk", "player_a", "player_b", "player_c", "player_d", "event", "shotype", "time", "Tm", "coordinates_x", "coordinates_y"]
with open('NHL_' + str(pk) + '_Indv_PBP.csv', "a", newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(my_data)
f.close()
JSON:
copyright "NHL and the NHL Shield a…8. All Rights Reserved."
gamePk 2017010001
link "/api/v1/game/2017010001/feed/live"
metaData {…}
gameData {…}
liveData
plays
allPlays
0 {…}
1 {…}
2 {…}
3 {…}
25 {…}
players
0 {…}
1 {…}
result
event "Shot"
eventCode "LAK15"
eventTypeId "SHOT"
description "Markus Granlund Snap Sho…saved by Jonathan Quick"
secondaryType "Snap Shot"
链接:https://statsapi.web.nhl.com/api/v1/game/2017010001/feed/live
答案 0 :(得分:1)
您应该在分配后检查shotype
。我相信你想要的是检查字典是否有特定的关键字,所以只需:
player_a, player_b, player_c, player_d = None, None, None, None
if 'result' in item:
result = item['result']
if 'secondaryType' in result:
shotype = result['secondaryType']
event = result['event']
if 'about' in item:
about = item['about']
if 'periodTime' in about:
time = about['periodTime']
# ... and so on