Python-如果u不是无:

Python-如果u不是无:,python,if-statement,Python,If Statement,我有一个脚本,我正试图刮取一个并不总是存在的键的值。我对我的IF声明有异议。这是如果shotType不是None我想要第二种类型的scrape,这种类型的快照只有在发生快照时才会出现 脚本: 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 = []

我有一个脚本,我正试图刮取一个并不总是存在的键的值。我对我的IF声明有异议。这是
如果shotType不是None
我想要第二种类型的scrape,这种类型的快照只有在发生快照时才会出现

脚本:

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()
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"
JSON:

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()
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"

链接:

您应该在作业后检查
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

您似乎在应该检查它的if语句之后定义了
shotype
变量。我尝试了多种不同的方法,但都没有成功使用open语句在
之后执行
f.close()
。上下文管理器自己处理文件关闭。谢谢提示