Have been playing with the undocumented NHL API for some days. I'd love to see any input about this little script. About overall structure, style, performance enhancements, etc. Not sure how to properly use long links in Python, should I even follow the PEP in this case? The same problem in a couple of other lines, it exceeds 79 symbols limit. Not sure if I should use pluses in the 'printed_info' lines, it behaves the same way without it, but some say it's more explicit, so it's better.
import requests
import json
import os
import collections
import timeit
import datetime
def basic_bio():
api_basic_bio = "http://www.nhl.com/stats/rest/skaters?isAggregate=false&reportType=basic&isGame=false&reportName=skaterpercentages&cayenneExp=gameTypeId=2%20and%20seasonId=20182019"
json_data = requests.get(api_basic_bio).json()
basic_full_bio_list = json_data["data"]
return basic_full_bio_list
def lastnames():
list_lastnames = []
players_range = range(len(basic_bio()))
json_bios = basic_bio()
for number in players_range:
list_lastnames.append((json_bios[number]["playerLastName"]).lower())
return list_lastnames
def duplicate_last_names():
last_names_count = collections.Counter(lastnames())
dup_last_names = {k: v for k, v in last_names_count.items() if v > 1}
return dup_last_names
def get_id_name_dict():
players_id_dict = {}
players_range = range(len(basic_bio()))
dups = duplicate_last_names()
skaters = basic_bio()
for number in players_range:
if (skaters[number]["playerLastName"]).lower() in dups:
players_id_dict[skaters[number]["playerName"].lower()] = skaters[number]["playerId"]
else:
players_id_dict[skaters[number]["playerLastName"].lower()] = skaters[number]["playerId"]
with open('nhl_skaters_id.json', 'w') as file:
file.write(json.dumps(players_id_dict, indent=4, sort_keys=True))
def get_id(player_lastname):
with open('nhl_skaters_id.json') as file:
data = json.load(file)
dups = duplicate_last_names()
if player_lastname in dups:
player_firstname = input("Enter a player's firstname: ").lower()
return data[player_firstname + ' ' + player_lastname]
else:
return data[player_lastname]
def get_stats(id):
api_base = 'https://statsapi.web.nhl.com/api/v1/people/'
api_end = '?hydrate=stats(splits=statsSingleSeason)'
url = ''.join([api_base, str(id), api_end])
json_data = requests.get(url).json()
stats = json_data["people"]
return stats
def show_stats(data):
path_stats = data[0]['stats'][0]['splits'][0]['stat']
path_bio = data[0]
printed_info = (f"Name: {path_bio['fullName']}\n\n" +
f"Birth Date: {path_bio['birthDate']}\n" +
f"Height: {path_bio['height']}\n" +
f"Weight: {path_bio['weight']}\n\n" +
f"Games: {path_stats['games']}\n" +
f"Goals: {path_stats['goals']}\n" +
f"Assists: {path_stats['assists']}\n" +
f"Points: {path_stats['points']}\n" +
f"PP Points: {path_stats['powerPlayPoints']}\n" +
f"Plus-minus: {path_stats['plusMinus']}\n" +
f"Shots: {path_stats['shots']}\n" +
f"Hits: {path_stats['hits']}\n" +
f"Blocks: {path_stats['blocked']}\n" +
f"Penalty Minutes: {path_stats['pim']}\n" +
f"TOI per Game: {path_stats['timeOnIcePerGame']}\n" +
f"PP TOI per Game: {path_stats['powerPlayTimeOnIcePerGame']}\n" +
f"SH TOI per Game: {path_stats['shortHandedTimeOnIcePerGame']}\n")
print(printed_info)
def data_old(file_name):
one_day_ago = datetime.datetime.now() - datetime.timedelta(days=1)
filetime = datetime.datetime.fromtimestamp(os.path.getmtime(file_name))
if filetime < one_day_ago:
return True
else:
return False
player_lastname = input("Enter a player's lastname: ").lower()
if os.path.isfile('nhl_skaters_id.json') == False or data_old('nhl_skaters_id.json') == True:
get_id_name_dict()
try:
data = get_stats(get_id(player_lastname))
print('-----------------------------')
show_stats(data)
except Exception:
print(f"{player_lastname.capitalize()} did't play any NHL games this season")