Graded = 8/8
In [1]:
import requests
response = requests.get('https://api.spotify.com/v1/search?query=Lil&type=artist&market=US&limit=50')
data = response.json()
In [2]:
# 1) With "Lil Wayne" and "Lil Kim" there are a lot of "Lil" musicians. Do a search and print a list of 50 that are playable in the USA (or the country of your choice), along with their popularity score.
# 2) What genres are most represented in the search results? Edit your previous printout to also display a list of their genres in the format "GENRE_1, GENRE_2, GENRE_3". If there are no genres, print "No genres listed".
artists = data['artists']['items']
genre_list = []
count = 1
for artist in artists:
genres = 'no genres listed'
if len(artist['genres']) > 0:
genres = str.join(", ", artist['genres'])
genre_list.extend(artist['genres'])
print("#" + str(count), str(artist['name']) + ":", str(artist['popularity']) + ",", genres)
count += 1
print("\n")
for genre in set(genre_list):
theCount = genre_list.count(genre)
if theCount == 1:
print("The genre", "“" + genre + "”", "appears once.")
else:
print("The genre", "“" + genre + "”", "appears", theCount, "times.")
In [3]:
# 3) Use a for loop to determine who BESIDES Lil Wayne has the highest popularity rating.
# Is it the same artist who has the largest number of followers?
# we scan the 'popularity' and 'followers' values
max_popularity = 0
most_popular_index = 0
max_followers = 0
most_followers_index = 0
max_range = len(artists)-1
for index in range(1, max_range): # we start at 1 to skip Lil Wayne
if artists[index]['popularity'] > max_popularity:
max_popularity = artists[index]['popularity']
most_popular_index = index
if artists[index]['followers']['total'] > max_followers:
max_followers = artists[index]['followers']['total']
most_followers_index = index
print("The most popular besides Lil Wayne is", str(artists[most_popular_index]['name']) + ".")
print("She has", artists[most_popular_index]['followers']['total'], "followers.")
print("With", artists[most_followers_index]['followers']['total'], "followers,", artists[most_followers_index]['name'], 'has the largest number of followers.')
# 4) Print a list of Lil's that are more popular than Lil' Kim.
# Lik' Kim has a popularity of 62.
more_popular = []
for artist in artists:
if artist['popularity'] > 62:
more_popular.append(artist['name'])
print("Following artists are more popular than Lil' Kim:", str.join(', ', more_popular) + ".")
In [4]:
# 5) Pick two of your favorite Lils to fight it out, and use their IDs to print out their top tracks.
# Tip: You're going to be making two separate requests, be sure you DO NOT save them into the same variable.
lil_1 = requests.get('https://api.spotify.com/v1/artists/4O15NlyKLIASxsJ0PrXPfz/top-tracks?country=US')
lil_1_data = lil_1.json()
lil_1_topTracks = []
for topTrack in lil_1_data['tracks']:
lil_1_topTracks.append(topTrack['name'])
print("Lil Uzi Vert's top tracks:", str.join(', ', lil_1_topTracks))
lil_2 = requests.get('https://api.spotify.com/v1/artists/6icQOAFXDZKsumw3YXyusw/top-tracks?country=US')
lil_2_data = lil_2.json()
lil_2_topTracks = []
for topTrack in lil_2_data['tracks']:
lil_2_topTracks.append(topTrack['name'])
print("Lil Boat's top tracks:", str.join(', ', lil_2_topTracks))
In [5]:
# 6) Will the world explode if a musicians swears?
# Get an average popularity for their explicit songs vs. their non-explicit songs.
tracks_count_Vert = {'exp': 0, 'non-exp': 0}
tracks_popularity_Vert = {'exp': 0, 'non-exp': 0}
tracks_ms_Vert = {'exp': 0, 'non-exp': 0}
for topTrack in lil_1_data['tracks']:
if topTrack['explicit'] == True:
tracks_count_Vert['exp'] += 1
tracks_popularity_Vert['exp'] += topTrack['popularity'] # currently: a sum
tracks_ms_Vert['exp'] += topTrack['duration_ms']
else:
tracks_count_Vert['non-exp'] += 1
tracks_popularity_Vert['non-exp'] += topTrack['popularity'] # currently: a sum
tracks_ms_Vert['non-exp'] += topTrack['duration_ms']
if tracks_count_Vert['exp'] > 0: # prevent division by 0
tracks_popularity_Vert['exp'] /= tracks_count_Vert['exp']
if tracks_count_Vert['non-exp'] > 0:
tracks_popularity_Vert['non-exp'] /= tracks_count_Vert['non-exp']
print("The average popularity of Lil Uzi Vert's explicit tracks is", tracks_popularity_Vert['exp'], "and the average popularity of her non-explicit tracks is", str(tracks_popularity_Vert['non-exp']) + '.')
# How many minutes of explicit songs do they have? Non-explicit?
print("Lil Uzi Vert has", "%.2f" % (tracks_ms_Vert['exp']/60000), "minutes of explicit songs and", "%.2f" % (tracks_ms_Vert['non-exp']/60000), "of non-explicit songs.")
tracks_count_Boat = {'exp': 0, 'non-exp': 0}
tracks_popularity_Boat = {'exp': 0, 'non-exp': 0}
tracks_ms_Boat = {'exp': 0, 'non-exp': 0}
for topTrack in lil_2_data['tracks']:
if topTrack['explicit'] == True:
tracks_count_Boat['exp'] += 1
tracks_popularity_Boat['exp'] += topTrack['popularity'] # currently: a sum
tracks_ms_Boat['exp'] += topTrack['duration_ms']
else:
tracks_count_Boat['non-exp'] += 1
tracks_popularity_Boat['non-exp'] += topTrack['popularity'] # currently: a sum
tracks_ms_Boat['non-exp'] += topTrack['duration_ms']
if tracks_count_Boat['exp'] > 0: # prevent division by 0
tracks_popularity_Boat['exp'] /= tracks_count_Boat['exp']
if tracks_count_Boat['non-exp'] > 0:
tracks_popularity_Boat['non-exp'] /= tracks_count_Boat['non-exp']
print("The average popularity of Lil Boat's explicit tracks is", tracks_popularity_Boat['exp'], "and the average popularity of her non-explicit tracks is", str(tracks_popularity_Boat['non-exp']) + '.')
# How many minutes of explicit songs do they have? Non-explicit?
print("Lil Boat has", "%.2f" % (tracks_ms_Boat['exp']/60000), "minutes of explicit songs and", "%.2f" % (tracks_ms_Boat['non-exp']/60000), "of non-explicit songs.")
In [6]:
# 7) Since we're talking about Lils, what about Biggies? How many total "Biggie" artists are there? How many total "Lil"s?
# If you made 1 request every 5 seconds, how long would it take to download information on all the Lils vs the Biggies?
# to be fair, we target the US market again
responseBig = requests.get('https://api.spotify.com/v1/search?query=Biggie&type=artist&market=US&limit=50')
dataBig = responseBig.json()
print("There is", data['artists']['total'], "results for “Lil” and", dataBig['artists']['total'], "for “Biggie”.")
print("It would take about", (data['artists']['total']*4500)/3600, "hours to get the results for the “Lil” and", (dataBig['artists']['total']*4500)/3600, "hours for the “Biggie”.")
In [7]:
# 8) Out of the top 50 "Lil"s and the top 50 "Biggie"s, who is more popular on average?
artistsBig = dataBig['artists']['items']
sumPopLil = 0
for artistLil in artists:
sumPopLil += artistLil['popularity']
sumPopBig = 0
for artistBig in artistsBig:
sumPopBig += artistBig['popularity']
print("The top 50 “Lil” is more popular, with an average popularity of", sumPopLil / len(artists), "vs.", str(sumPopBig / len(artistBig)) + " for the 49 “Biggie”.")
In [ ]:
# LIL' GRAPHICS
# # Just a simple bar graph of their various popularities sounds good to me.
# NB: Maybe you'll need to run this code twice in order for d3.js to be fully loaded
from IPython.display import display, HTML
artistNames = []
artistPop = []
for artistLil in artists:
artistNames.append(artistLil['name'])
artistPop.append(artistLil['popularity'])
html = []
html.append('<style>.chart div { font: 10px sans-serif; background-color: steelblue; text-align: right; padding: 3px; margin: 1px; color: white;}</style><div class="chart"></div><script src="http://d3js.org/d3.v3.min.js"></script>')
html.append('<script>')
html.append('var lil_data = ' + str(artistPop) + ';')
html.append('var lil_names = ' + str(artistNames) + ';')
html.append('var x = d3.scale.linear() .domain([0, d3.max(lil_data)]) .range([0, 420]);d3.select(".chart") .selectAll("div") .data(lil_data) .enter().append("div") .style("width", function(d) { return x(d) + "px"; }) .text(function(d, i) { return lil_names[i] + ": " + d; });</script></body></html>')
d3Graph = str.join('', html)
# Uncomment next line to generate the graph dynamically:
#display(HTML(d3Graph))
Screen capture of the graph for the static page:
In [ ]:
# SEARCH ENGINE
#
# Make a non-IPython Notebook that automates browsing for top tracks
# Prompts for an artist
requested_artist = input("Search for…\n")
search_result = requests.get('https://api.spotify.com/v1/search?query=' + requested_artist + '&type=artist')
search_result_data = search_result.json()
artists_result = search_result_data['artists']['items']
length_result = len(artists_result)
print(length_result, "results!")
for i in range(1, length_result+1):
print('#' + str(i), artists_result[i-1]['name'])
# you put it in, displays the results, asks which one you want (numbered)
wanted_artist = input("\nWhich one do you want?\n")
# Never trust users
try:
wanted_artist_int = int(wanted_artist)-1
except ValueError:
print("Next time, please choose an integer. I picked up number 1 for you.")
wanted_artist_int = 0
if wanted_artist_int < 0 or wanted_artist_int > length_result-1:
print("This number is out of range.")
else:
wanted_artist_id = artists_result[wanted_artist_int]['id']
print("\nRetrieving information about", artists_result[wanted_artist_int]['name'] + "...\n")
# Display their top tracks
wanted_tracks = requests.get('https://api.spotify.com/v1/artists/' + wanted_artist_id + '/top-tracks?country=US')
wanted_tracks_data = wanted_tracks.json()
theTrackResults = []
for topTrack in wanted_tracks_data['tracks']:
theTrackResults.append(topTrack['name'])
if len(theTrackResults) > 1:
print("Top tracks:", str.join(', ', theTrackResults))
else:
print("Top track:", str.join(', ', theTrackResults))
# Their MOST popular album and their least popular album.
# 1) We retreive the ids of the albums
wanted_albums = requests.get('https://api.spotify.com/v1/artists/' + wanted_artist_id + '/albums')
wanted_albums_data = wanted_albums.json()
album_id_list = []
for album in wanted_albums_data['items']:
album_id_list.append(album['id'])
# 2) We load these albums to get their popularity
search_result = requests.get('https://api.spotify.com/v1/albums/?ids=' + str.join(',',album_id_list))
search_result_data = search_result.json()
albums = search_result_data['albums']
album_hits = len(albums)
if(album_hits) < 1:
print("No album could be retrieved.")
elif(album_hits) == 1:
print("This artist has only one album on Spotify: “" + str(albums[0]['name']) + "”.")
else:
album_popularity = []
album_name = []
for album in albums:
album_popularity.append(album['popularity'])
album_name.append(album['name'])
print("\n" + str(album_hits), "albums found.")
most_popular_album_index = album_popularity.index(max(album_popularity))
least_popular_album_index = album_popularity.index(min(album_popularity))
print("The album “" + album_name[most_popular_album_index] + "” is the most popular, with a popularity score of", str(album_popularity[most_popular_album_index]) + ".")
print("The album “" + album_name[least_popular_album_index] + "” is the least popular, with a popularity score of", str(album_popularity[least_popular_album_index]) + ".")