This script will suggest playlists based on the text of your choice. For example, if you enter 'If I can't let it go out of my mind' [the default value], your playlist may include songs titled 'Out of my mind'. You also need to specify the number of track suggested [default value is 3]. The first time you run this script, it will ask authorization to access your Spotify account. The script also needs the 'Spotify' library installed in your system.

To start, please tell me the text you want to match and the number of playlists


In [1]:
#install spotipy
! pip install spotipy
#This command above only from Jupyter notebooks

# Load Libraries
import math
import spotipy
import spotipy.util as util

#Request User Input
cuesline = input("Enter your text here [Default: 'If I can't let it go out of my mind'] : ")
playlistno = input("Enter the number of playlists you want to generate? [Default: 3] : ")


Requirement already satisfied: spotipy in c:\users\elias\anaconda3\lib\site-packages
Requirement already satisfied: requests>=1.0 in c:\users\elias\anaconda3\lib\site-packages (from spotipy)
Enter your text here [Default: 'If I can't let it go out of my mind'] : ""
Enter the number of playlists you want to generate? [Default: 3] : 19

In [2]:
#Handle Missing Input/Error in Entry
default = "If I can't let it go out of my mind"
try:
    if not bool(cuesline.strip()) or cuesline in ('','""',"''"):
        cuesline = default
        print ("")
        print ("Using text default value:",default)
        
except:
    cuesline = default
    print ("")
    print ("Using text default value:",default)

cues = cuesline.split()

try:
    playlistno = eval(playlistno)
    if playlistno<=0:
        if len(cues)>=3:
            playlistno = 3
            print ("")
            print ("Using default value of",playlistno,"playlists")
        else:
            playlistno = len(cues)
            print ("")
            print ("Your text contains less than 3 words, I'll search for",playlistno," playlists")

    elif playlistno>len(cues):
        playlistno = len(cues)
        print ("")
        print ("Maximum playlists per your text is",len(cues))
except:
    if len(cues)>=3:
        playlistno = 3
        print ("")
        print ("Using default value of",playlistno,"playlists")

    else:
        playlistno = len(cues)
        print ("")
        print ("Your text contains less than 3 words, I'll search for",playlistno," playlists")
     
#Split blocks of text in parts based on tracks requested
cues = cuesline.split()
phraseslength = math.floor(len(cues)/playlistno)

cueswords=[]
for index in range(playlistno):
    if index + 1 == playlistno:
        cueswords.append(' '.join(cues[(index)*phraseslength:]))
        break
    cueswords.append(' '.join(cues[index*phraseslength:phraseslength*(index+1)]))


Using text default value: If I can't let it go out of my mind

Maximum playlists per your text is 10

Now you may need to authorize this app to access your playlist, your browser will direct you to a new page, copy and paste the URL in the form below


In [3]:
# Connect to Spotify API
client_id='95df4271622e424b84e1dd2a48233907'
client_secret='e81854a1889a4285ab29bf1d41b9009b'
redirect_uri='http://localhost:8888/callback'
scope = 'playlist-modify-public'

class credentials():
    def __init__(self,name):
        global username
        self.username=name
        token = util.prompt_for_user_token(self.username, scope,client_id, client_secret,redirect_uri)
        self.sp = spotipy.Spotify(auth=token)
        username=self.username

credentials("")
token = util.prompt_for_user_token(username,scope,client_id,client_secret,redirect_uri)

In [4]:
#Generate playlist urls
print('')
print("These are my suggested playlists:")
print("")

if token:
    sp = spotipy.Spotify(auth=token)
    sp.trace = False

    for x in range(0,len(cueswords)):
        if cueswords[x]=='':
            print ("Bummer!. Some playlists were not found!")
            break
        results = sp.search(q=str(cueswords[x]), limit=1)
        if results['tracks']['items']==[]:
                print ("Bummer!. Some playlists were not found!")
        for i, t in enumerate(results['tracks']['items']):
            
            print(''.join(['Playlist #',str(x+1),':']),t['name'],"@",''.join(["https://open.spotify.com/track/",t['id']]))
else:
    print("Can't get token for", username)

print("")
print("You are welcome!")


These are my suggested playlists:

Playlist #1: If I Told You @ https://open.spotify.com/track/6PjIjfiTS6OMft5HXuW2PV
Playlist #2: Bounce Back @ https://open.spotify.com/track/0SGkqnVQo9KPytSri1H6cF
Playlist #3: Can’t Let Go, Juno @ https://open.spotify.com/track/21BWdXsBx3CfHuuj36RWS5
Playlist #4: Let Me Explain @ https://open.spotify.com/track/1trZGMI2CGyVT44STkpCoN
Playlist #5: It Ain’t Me (with Selena Gomez) @ https://open.spotify.com/track/12GEpg2XOPyqk03JZEZnJs
Playlist #6: Go Flex @ https://open.spotify.com/track/5yuShbu70mtHXY0yLzCQLQ
Playlist #7: First Day Out @ https://open.spotify.com/track/3muBQDekYAg7jm6hDu6R0Z
Playlist #8: Shape of You @ https://open.spotify.com/track/0FE9t6xYkqWXU2ahLh6D8X
Playlist #9: Redbone @ https://open.spotify.com/track/3kxfsdsCpFgN412fpnW85Y
Playlist #10: We Don't Talk Anymore (feat. Selena Gomez) @ https://open.spotify.com/track/37FXw5QGFN7uwwsLy8uAc0

You are welcome!