如何处理Discogs API响应并将数据提取到列表中

2024-05-22 09:36:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在解析来自DISCOGS的API响应时遇到问题,我对使用API还不熟悉

我想做的是对discogs进行API调用,然后接收API响应,然后从响应中提取艺术家id号和名称,并将其存储到列表中

是否有一种简单的方法可以获取API响应数据,如下所示:

[<Master 22755 "The Party's Over">, <Master 22872 'Talk Talk'>, <Master 22902 "Today • It's So Serious">, <Master 158230 'Mirror Man'>] # subset of the api response data

并生成一个简单的列表,如下所示:

[["22755", "The Party's Over"], ["22872", "Talk Talk"], ["22902","Today • It's So Serious"],["158230", "Mirror Man"]]

关于背景信息,我用于进行api调用的代码是:

import discogs_client, re

# api docs
# https://github.com/grawlinson/python-discogs-api
 
# Autheticate on API
d = discogs_client.Client('discogs_api.py', user_token="Get from Discogs User Account")
# releases = d.search('talk talk', type='artist')
# print(releases)
 
# Use the API to find the band name and discog id 
results = d.search("Talk Talk", type='release')
results.pages
artist = results[0].artists[0]
artist.name
name = artist.name
print(name)
discogs_id = artist.id
print(id)

# API call for albums details
artist = d.artist(discogs_id)
print(artist.releases.page(1))

Api将返回以下内容:

# example from api response

[<Master 22755 "The Party's Over">, <Master 22872 'Talk Talk'>, <Master 22902 "Today • It's So Serious">, <Master 158230 'Mirror Man'>] 

# when I check the type python tells me its: <class 'list'>

然后,我尝试了以下代码来解析API响应数据:

# Turn API data into a List and make a list of lists

lista = artist.releases.page(1)
title_list_of_lists = []
title_list = []
for i in lista:
    i = str(i)
    title_list_of_lists.append([i])
print(title_list_of_lists)
print(type(title_list_of_lists))


# Split the list of list into two elements per sub list

listb = []
n = 0
for i in range(len(title_list_of_lists)):
    for j in title_list_of_lists[i]:
        k = j.split(maxsplit=2)
        listb.append(k[1:])
    n= n+1
print(listb)

# the output is :

[['<Master 22755 "The Party\'s Over">'], ["<Master 22872 'Talk Talk'>"], ['<Master 22902 "Today • It\'s So Serious">'], ["<Master 158230 'Mirror Man'>"]]


Thanks

Tags: ofthenamemasterapiiddiscogstitle