繁体   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