第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Spotipy/Spotify API 的“else”序列問題

使用 Spotipy/Spotify API 的“else”序列問題

尚方寶劍之說 2023-12-12 15:02:57
我和我的團隊(Python 新手)編寫了以下代碼來生成與特定城市和相關(guān)術(shù)語相關(guān)的 Spotify 歌曲。如果用戶輸入的城市不在我們的 CITY_KEY_WORDS 列表中,那么它會告訴用戶輸入將添加到請求文件中,然后將輸入寫入文件。代碼如下:from random import shufflefrom typing import Any, Dict, Listimport spotipyfrom spotipy.oauth2 import SpotifyClientCredentialssp = spotipy.Spotify(    auth_manager=SpotifyClientCredentials(client_id="",                                          client_secret=""))CITY_KEY_WORDS = {    'london': ['big ben', 'fuse'],    'paris': ['eiffel tower', 'notre dame', 'louvre'],    'manhattan': ['new york', 'new york city', 'nyc', 'empire state', 'wall street', ],    'rome': ['colosseum', 'roma', 'spanish steps', 'pantheon', 'sistine chapel', 'vatican'],    'berlin': ['berghain', 'berlin wall'],}def main(city: str, num_songs: int) -> List[Dict[str, Any]]:    if city in CITY_KEY_WORDS:        """Searches Spotify for songs that are about `city`. Returns at most `num_songs` tracks."""        results = []        # Search for songs that have `city` in the title        results += sp.search(city, limit=50)['tracks']['items']  # 50 is the maximum Spotify's API allows        # Search for songs that have key words associated with `city`        if city.lower() in CITY_KEY_WORDS.keys():            for related_term in CITY_KEY_WORDS[city.lower()]:                results += sp.search(related_term, limit=50)['tracks']['items']        # Shuffle the results so that they are not ordered by key word and return at most `num_songs`        shuffle(results)        return results[: num_songs]該代碼對于“if”語句運行良好(如果有人進入我們列出的城市)。但是,當(dāng)運行 else 語句時,在操作正常執(zhí)行后會出現(xiàn) 2 個錯誤(它將用戶的輸入打印并寫入文件)。出現(xiàn)的錯誤是:Traceback (most recent call last):  File "...", line 48, in <module>    display_tracks(tracks)  File "...", line 41, in display_tracks    for num, track in enumerate(tracks):TypeError: 'NoneType' object is not iterable請原諒我缺乏知識,但請有人幫忙解決這個問題嗎?我們還想在最后創(chuàng)建一個歌曲的播放列表,但在這方面遇到了困難。
查看完整描述

2 回答

?
九州編程

TA貢獻1785條經(jīng)驗 獲得超4個贊

您的函數(shù)在子句中main沒有語句,這會導(dǎo)致be 。迭代何時是導(dǎo)致錯誤的原因。您可以采取一些措施來改進代碼:returnelsetracksNonetracksNone

  • 關(guān)注點分離:該main函數(shù)正在做兩件不同的事情,檢查輸入和獲取曲目。

  • 一開始就做.lower()一次,這樣就不必重復(fù)。

  • 遵循文檔約定。

  • 使用前檢查響應(yīng)

  • 一些代碼清理

請參閱下面我上面建議的更改:

def fetch_tracks(city: str, num_songs: int) -> List[Dict[str, Any]]:

    """Searches Spotify for songs that are about `city`.


    :param city: TODO: TBD

    :param num_songs:  TODO: TBD

    :return: at most `num_songs` tracks.

    """

    results = []

    for search_term in [city, *CITY_KEY_WORDS[city]]:

        response = sp.search(search_term, limit=50)

        if response and 'tracks' in response and 'items' in response['tracks']:

            results += response['tracks']['items']

    # Shuffle the results so that they are not ordered by key word and return

    # at most `num_songs`

    shuffle(results)

    return results[: num_songs]



def display_tracks(tracks: List[Dict[str, Any]]) -> None:

    """Prints the name, artist and URL of each track in `tracks`"""

    for num, track in enumerate(tracks):

        # Print the relevant details

        print(

            f"{num + 1}. {track['name']} - {track['artists'][0]['name']} "

            f"{track['external_urls']['spotify']}")



def main():

    city = input("Virtual holiday city? ")

    city = city.lower()

    # Check the input city and handle unsupported cities.

    if city not in CITY_KEY_WORDS:

        print("Unfortunately, this city is not yet in our system. "

              "We will add it to our requests file.")

        with open('requests.txt', 'a') as f:

            f.write(f"{city}\n")

        exit()


    number_of_songs = input("How many songs would you like? ")

    tracks = fetch_tracks(city, int(number_of_songs))

    display_tracks(tracks)



if __name__ == '__main__':

    main()


查看完整回答
反對 回復(fù) 2023-12-12
?
慕標(biāo)琳琳

TA貢獻1830條經(jīng)驗 獲得超9個贊

當(dāng)if執(zhí)行 - 語句時,您將返回一個項目列表并將它們輸入到display_tracks()函數(shù)中。else但是執(zhí)行 - 語句時會發(fā)生什么?您將請求添加到文本文件中,但不返回任何內(nèi)容(或項目NoneType)并將其輸入到display_tracks(). display_tracks然后迭代此NoneType-item,拋出異常。


您只想在確實有任何要顯示的曲目時顯示曲目。實現(xiàn)此目的的一種方法是將 的調(diào)用display_tracks()移至您的main函數(shù)中,但是如果沒有找到您的搜索項的曲目,則會引發(fā)相同的錯誤。另一個解決方案是首先檢查您的內(nèi)容是否tracks不為空,或者使用類似的方法捕獲TypeError- 異常


tracks = main(city, int(number_of_songs))

try:

    display_tracks(tracks)

except TypeError:

    pass


查看完整回答
反對 回復(fù) 2023-12-12
  • 2 回答
  • 0 關(guān)注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號