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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

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

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

尚方寶劍之說 2023-12-12 15:02:57
我和我的團(tuán)隊(duì)(Python 新手)編寫了以下代碼來生成與特定城市和相關(guān)術(shù)語相關(guān)的 Spotify 歌曲。如果用戶輸入的城市不在我們的 CITY_KEY_WORDS 列表中,那么它會(huì)告訴用戶輸入將添加到請(qǐng)求文件中,然后將輸入寫入文件。代碼如下: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]該代碼對(duì)于“if”語句運(yùn)行良好(如果有人進(jìn)入我們列出的城市)。但是,當(dāng)運(yùn)行 else 語句時(shí),在操作正常執(zhí)行后會(huì)出現(xiàn) 2 個(gè)錯(cuò)誤(它將用戶的輸入打印并寫入文件)。出現(xiàn)的錯(cuò)誤是: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請(qǐng)?jiān)徫胰狈χR(shí),但請(qǐng)有人幫忙解決這個(gè)問題嗎?我們還想在最后創(chuàng)建一個(gè)歌曲的播放列表,但在這方面遇到了困難。
查看完整描述

2 回答

?
九州編程

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊

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

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

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

  • 遵循文檔約定。

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

  • 一些代碼清理

請(qǐ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()


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

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊

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


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


tracks = main(city, int(number_of_songs))

try:

    display_tracks(tracks)

except TypeError:

    pass


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

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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