簡體   English   中英

使用 Spotipy 從 Python 中的打印中獲取特定行

[英]Getting specific lines from a print in Python with Spotipy

我正在用 Python 和 Spotipy 編寫一些代碼,而且我對編碼還比較陌生。 我有一些代碼可以獲取有關 Spotify 播放列表的所有信息並為我打印出來:

from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
import json


client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

playlist_id = 'spotify:playlist:76CVeJDw2b90up5PgkZXyU'
results = sp.playlist(playlist_id)
#print(json.dumps(results, indent=4))
print((json.dumps(results, indent=4)))

它運作良好,並為我提供了所有信息。 我的問題是我只需要打印中的細節:

  "collaborative": false,
    "description": "",
    "external_urls": {
        "spotify": "https://open.spotify.com/playlist/76CVeJDw2b90up5PgkZXyU"
    },
    "followers": {
        "href": null,
        "total": 0
    },
    "href": "https://api.spotify.com/v1/playlists/76CVeJDw2b90up5PgkZXyU?additional_types=track",
    "id": "76CVeJDw2b90up5PgkZXyU",
    "images": [
        {
            "height": 640,
            "url": "https://i.scdn.co/image/ab67616d0000b2734a052b99c042dc15f933145b",
            "width": 640
        }
    ],
    "name": "TEST",
    "owner": {
        "display_name": "Name",
        "external_urls": {
            "spotify": "https://open.spotify.com/user/myname"
        },
        "href": "https://api.spotify.com/v1/users/myname",
        "id": "Myname",
        "type": "user",
        "uri": "spotify:user:kovizsombor"
    },
    "primary_color": null,
    "public": true,
    "snapshot_id": "MixmMGE0MDgxNDQ1ZGVlNmE4MThiMmQwODMwYWU0OTI3YzkyOGJhOWIz",
    "tracks": {
        "href": "https://api.spotify.com/v1/playlists/76CVeJDw2b90up5PgkZXyU/tracks?offset=0&limit=100&additional_types=track",
        "items": [
            {
                "added_at": "2020-05-17T10:00:11Z",
                "added_by": {
                    "external_urls": {
                        "spotify": "https://open.spotify.com/user/kovizsombor"
                    },
                    "href": "https://api.spotify.com/v1/users/kovizsombor",
                    "id": "kovizsombor",
                    "type": "user",
                    "uri": "spotify:user:kovizsombor"
                },
                "is_local": false,
                "primary_color": null,
                "track": {
                    "album": {
                        "album_type": "album",
                        "artists": [
                            {
                                "external_urls": {
                                    "spotify": "https://open.spotify.com/artist/0PFtn5NtBbbUNbU9EAmIWF"
                                },
                                "href": "https://api.spotify.com/v1/artists/0PFtn5NtBbbUNbU9EAmIWF",
                                "id": "0PFtn5NtBbbUNbU9EAmIWF",
                                "name": "TOTO",
                                "type": "artist",
                                "uri": "spotify:artist:0PFtn5NtBbbUNbU9EAmIWF"
                            }
                        ],

                        ],
                        "external_urls": {
                            "spotify": "https://open.spotify.com/album/62U7xIHcID94o20Of5ea4D"
                        },
                        "href": "https://api.spotify.com/v1/albums/62U7xIHcID94o20Of5ea4D",
                        "id": "62U7xIHcID94o20Of5ea4D",
                        "images": [
                            {
                                "height": 640,
                                "url": "https://i.scdn.co/image/ab67616d0000b2734a052b99c042dc15f933145b",
                                "width": 640
                            },
                            {
                                "height": 300,
                                "url": "https://i.scdn.co/image/ab67616d00001e024a052b99c042dc15f933145b",
                                "width": 300
                            },
                            {
                                "height": 64,
                                "url": "https://i.scdn.co/image/ab67616d000048514a052b99c042dc15f933145b",
                                "width": 64
                            }
                        ],
                        "name": "Toto IV",
                        "release_date": "1982-04-08",
                        "release_date_precision": "day",
                        "total_tracks": 10,
                        "type": "album",
                        "uri": "spotify:album:62U7xIHcID94o20Of5ea4D"
                    },
                    "artists": [
                        {
                            "external_urls": {
                                "spotify": "https://open.spotify.com/artist/0PFtn5NtBbbUNbU9EAmIWF"
                            },
                            "href": "https://api.spotify.com/v1/artists/0PFtn5NtBbbUNbU9EAmIWF",
                            "id": "0PFtn5NtBbbUNbU9EAmIWF",
                            "name": "TOTO",
                            "type": "artist",
                            "uri": "spotify:artist:0PFtn5NtBbbUNbU9EAmIWF"
                        }
                    ],
                    "available_markets": [

                    ],
                    "disc_number": 1,
                    "duration_ms": 295893,
                    "episode": false,
                    "explicit": false,
                    "external_ids": {
                        "isrc": "USSM19801941"
                    },
                    "external_urls": {
                        "spotify": "https://open.spotify.com/track/2374M0fQpWi3dLnB54qaLX"
                    },
                    "href": "https://api.spotify.com/v1/tracks/2374M0fQpWi3dLnB54qaLX",
                    "id": "2374M0fQpWi3dLnB54qaLX",
                    "is_local": false,
                    "name": "Africa",
                    "popularity": 83,
                    "preview_url": "https://p.scdn.co/mp3-preview/dd78dafe31bb98f230372c038a126b8808f9349b?cid=d568e7073a38465bba48268ea9f10153",
                    "track": true,
                    "track_number": 10,
                    "type": "track",
                    "uri": "spotify:track:2374M0fQpWi3dLnB54qaLX"
                },
                "video_thumbnail": {
                    "url": null
                }
            }
        ],
        "limit": 100,
        "next": null,
        "offset": 0,
        "previous": null,
        "total": 1
    },
    "type": "playlist",
    "uri": "spotify:playlist:76CVeJDw2b90up5PgkZXyU"
}

從這個長長的打印中,我需要以某種方式提取藝術家和歌曲標題,並最好將其變成一個變量。 如果播放列表中有多首歌曲,也不確定這將如何工作。

如果我可以只打印出藝術家和歌曲的標題而不打印出所有信息,這也是一個解決方案。

sp.playlist返回一個字典,因此您可以通過它們的鍵簡單地訪問它的值。 例如:

>>> results['name']
'TEST'

JSON 是一種數據序列化格式,即將對象表示為純文本並從文本中解析回來的標准化方式。 json.dumps因此將字典 object 轉換為文本字符串。 例如,如果您想將結果保存到文件中並稍后將其加載回來,這將非常有用。 您不需要它來訪問results中的內容。

(不過,這是一個播放列表——您需要獲取每首歌曲/曲目的信息以獲取其藝術家和名稱。)

根據您發布的示例,您似乎只有一首由藝術家“TOTO”命名為“Africa”的歌曲。 復制曲目以獲得兩首歌曲,我添加了另一首曲目,其中有兩位藝術家用於測試 arrays。

如果將 json 加載到名為results的變量中,那么(如@xcmkz 所說)您有一個 python 字典,可以進行相應的處理。

嘗試使用以下內容橫向瀏覽您的 dict,將藝術家和歌曲添加到列表中:

song_dict = {}
for track in results['tracks']['items']:
    song_name = track["track"]["name"]
    a2 = []
    for t1 in track['track']['artists']:
        a2.append(t1['name'])
        song_dict.update({song_name: a2})

print(f'Dictionary of Songs and Artists:')
for k, v in song_dict.items():
    print(f'Song --> {k}, by --> {", ".join(v)}')

結果:

Dictionary of Songs and Artists:
Song --> Africa, by --> TOTO
Song --> Just Another Silly Song, by --> Artist 2, Artist 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM