Spotipy音频功能返回类型错误

时间:2019-04-25 19:16:45

标签: python python-3.x spotify spotipy

我正在使用Spotipy与Spotify API进行交互。我已经成功地从艺术家,唱片和每张唱片的曲目中获取信息。我可以获取曲目ID,名称和受欢迎程度。但是,当我尝试使用音频功能获取价时,它不起作用。

这是我的代码:

for a in artists_array
    artist_search = sp.search(a,1,0,"artist")
    artist = artist_search['artists']['items'][0]
    artists.append({'name': artist['name'], 'popularity': artist['popularity']})

    albums = []
    albums_ids = []
    spotify_albums = sp.artist_albums(artist['id'], album_type='album')
    for i in range(len(spotify_albums['items'])):
        album_id = spotify_albums['items'][i]['id']
        albums_ids.append(spotify_albums['items'][i]['id'])
        album_name = spotify_albums['items'][i]['name']
        albums.append({'id': album_id,'name': album_name })

    albums_songs = []
        albumIndex = 0;
        #For each album
        for id in albums_ids:
        albums_songs.append([])
        spotify_songs = sp.album_tracks(id)
        for n in range(len(spotify_songs['items'])):
            song_id = spotify_songs['items'][n]['id']
            song_name = spotify_songs['items'][n]['name']
            song_popularity = sp.track(song_id)['popularity']
            song_valence = sp.audio_features([song_id])['valence']
            albums_songs[albumIndex].append({'id': song_id, 'name': song_name, 'album_id': id, 'popularity': song_popularity, 'valence': song_valence })

问题出在:

 song_valence = sp.audio_features(song_id)['valence']

抛出:

Traceback (most recent call last):
  File "spotifyAPI/server.py", line 110, in <module>
    song_valence = sp.audio_features(list_song_id[0])['valence']
TypeError: list indices must be integers or slices, not str

我知道我有正确的song_id,因为它可以提高人气。如果我删除价部分,该程序将完美运行。

我不了解类型错误。根据Spotipy,我应该给出:

  

audio_features(tracks = [])   根据它们的Spotify ID获取一个或多个轨道的音频功能参数:tracks-的列表   跟踪URI,URL或ID,最多:50个ID

这就是我这样说的原因:

song_valence = sp.audio_features([song_id])['valence']

但这也不适用于

song_valence = sp.audio_features(song_id)['valence']

1 个答案:

答案 0 :(得分:0)

我找到了解决方案!如果有人遇到同样的问题,请留在这里。它需要一个列表,该列表可以只是您想要的song_id,然后您需要在索引0处进行访问。希望这会有所帮助

list_song_ids = [song_id]
song_valence = sp.audio_features(list_song_ids)[0]['valence']