1

我正在尝试通过 python 使用 MusicBrainz API,并且在试图弄清楚为什么在满足特定条件后我的循环不会中断的时候,我感到很痛苦。我通过获取 JSON 的 URL 传递歌曲的持续时间和声学 ID。我不确定 JSON 是否无效,但可以使用格式化的输出。我被卡住的部分是尽管我告诉代码在歌曲的持续时间与返回的 JSON 的持续时间匹配时中断,但它仍然继续显示与持续时间匹配的其余数据。此外,我得到一个主要数据元素的 KeyError,这对我来说看起来不错!请帮忙!

正在使用的 Python 代码:

import urllib2
import urllib
import simplejson
import json
import pprint

duration = 266
output = 'AQABz0q6JJFknHgOHH0q9DyQw8lxIzmaLzl6HHyE7yO6G4dP9Mc3JDry4FJR5RfIvccWH0d_PD-O63gi9KTQPjme4-uDxl04hMqcQf0RfXgmKWDSDD8aF9dYTDl5hEPy46gnHY-iPEWZEWfw42

-

SIHZiQQ9xLR90ckzRw_mNez_aHZeeQnlIIdfxyHieBLl0HC_Y_Ajpo3lxnMf7DJUleJKGhk_Bw7mCvAqS53j1CE30BFdmYqeOL3pQ8vgeNAqzfKjMx_jRJ0dTMT_yZziuIE6ko1kSzcG7BMZzCU13JTglGZ9x

pcVJKgjlHAlfnFGONw8uHo-xd8Pn46DGDMmeI-fx5Vid6LjwXCLKh2h-5IPy8LiP3iUsaoGU9PixE3_wZEcyqw0O_MPhiugffMcfxNSJJMcbfMqagtMDH9eP5-AfJF-OMMtRUTl4JWiebA-

MnsazIzmDHP9QHU2DL-CTTMGHIfihXwqe6PjR_ugPnTlyXDmehGmCW5KDUHkO8Qg7HDPBJ8dP_MGlBHp-HD8uRuBewnoxvtCTwkvUCaeOH01MWA9ON0hupItyNJNSPELzZ-hFxAp1DXJ8nEolQu-

PtGLwED_gmMfzG3fw9Hhx3mhe1Do-o5KmVIG1M8MTIdmP8D_MMagTUsaP9sd_WKg-H6eRejm-J4TOHHPyEFVPkN9Ri-HA_A6aHlcu4Tn6KHiM99iRujGe42iO48eP-0WTRoOToxb-

o9nR99jR1EF_hImzrEEyJXyGiRnTwx8qo9E4H1VzPMKDvoMd-gjlLIS2C442UmhzDc-O-

kVDIdePZ0dvorlwZbrw5McTP5i8Hc1jXEH0vDiEP9ilK7iUQ6qkY3qQPsNFNJoY462JL_gZoTlC10geTc5xqRPxDMWOivIOMj_e402RPEGu4R2ancKfww9YJfB3CdP34D6eHiG1FXPESRxcHf6hPfh6nJskZH

Ke4DTW4w8-4wkf4sqHnkd6JCcuGl6SPCgZnMeYJiPuhbh1RGIeJMSN_3imwi4HeImeo5SOS7ij5HiMK7oQnhf0C-l0_KjUrPhx7_hxXDpC2IGmPMV_FT-

Rq8aTAukX_BfU_EXOxXCTLMQlC89yPPnRZEGeC82kRGSgMzx6Isx0Ia4uPJEY9PLR9Hg04w90mEN-CfuONvrhH4ezDQ8TjEeYc9CeHmGqHD8qZ4dVnEc_41R0NAqPaj2aNQ-eIm1zI-dxZzme-

HjQkuiLH36RM0j4oD8-EueDLjE8EvUyfBc-hhF-

C8n4IH1QncELRoFTgjADFCCKdIOIBYQZ0UABgDAnsAGCQuGEAgwhwACGDBFgMIIAAQKsMIQY4QARQFAAiJGeEQOoBEgpEZxQAAEipDAOEYCEAU4AZAEBQAoYDGFAMGKIwIIRgIg4jiDFlIAAIEIEBMwwBJQkX

hiohHEGIKAkcsIp4RAigAHBgPKSAKIIAoAxgJBjlhhkCIDAIAQkIgYAKSyQCDpCARIESWUAMYQ4YQGzGhhkADBAEOIEMAAhZRlQRgGkBBECMeAIQYAghxBAChAigANEIWKQcEbB5ZxlChGKACCAEKWEsIIyiw

RiTAABgBNKAAIIQMQhJCCoTAgliAIAICYwAIRZowRgxCllDBOAAEGABQIRoQ0ABIFgHCEECSEUMhQBAhkDwABCBANIACSABMxoAYGEBFRCASBEGAMBEMAIxBQQABkkLALAAIaIYIwggoACShgEjLEKAQ0AQsY

goBwAAImMFBBIQQUUQcgQARQI'
data = {}
data['client'] = '8XaBELgH'
data['format'] = 'json'
data['meta'] = '2'
data['duration'] = str(duration)
data['fingerprint'] = output
resp = urllib2.urlopen('http://api.acoustid.org/v2/lookup', urllib.urlencode(data))
str_to_load = resp.read()
json = simplejson.loads(str_to_load)
#pprint.pprint(json)
for result in json['results']:
    for recording in result['recordings']:
        for track in recording['tracks']:
            track_artist = ''
            for artist in track['artists']:
                try:
                    track_artist += repr(artist['name']) + ' '
                except:
                    track_artist = ''
            #print str(track['duration']) + '-' + track['medium']['release']['title'] + '-' + track['title'] + '-' + track_artist
            if str(track['duration']) == str(duration):
                print 'Matched:' + str(track['duration']) + '-' + track['medium']['release']['title'] + '-' + track['title'] + '-' + track_artist
                break

返回的 JSON:

{
    "status": "ok",
    "results": [{
        "recordings": [{
            "duration": 264,
            "tracks": [{
                "duration": 264,
                "position": 7,
                "medium": {
                    "release": {
                        "id": "036ce98e-0397-4ddb-97ff-e6784fdd21a4",
                        "title": "Live in Paris"
                    },
                    "position": 1,
                    "track_count": 10,
                    "format": "CD"
                },
                "artists": [{
                    "id": "3cb25fb2-5547-4b05-adec-1a5e37830d46",
                    "name": "Lionel Richie"
                }],
                "title": "Sail On"
            }],
            "id": "0083c88e-1ca2-484e-b1ff-d384358942bb"
        }, {
            "duration": 268,
            "tracks": [{
                "duration": 268,
                "position": 12,
                "medium": {
                    "release": {
                        "id": "9c0a98e8-da23-49cf-a6ae-df27340deebb",
                        "title": "Love Songs"
                    },
                    "position": 1,
                    "track_count": 16,
                    "format": "CD"
                },
                "artists": [{
                    "id": "60d41417-feda-4734-bbbf-7dcc30e08a83",
                    "name": "Diana Ross"
                }, {
                    "id": "3cb25fb2-5547-4b05-adec-1a5e37830d46",
                    "name": "Lionel Richie"
                }],
                "title": "Endless Love"
            }],
            "id": "07be8b05-a1cb-4e88-8217-2ef5e0dafcb3"
        }, {
            "duration": 267,
            "tracks": [{
                "duration": 267,
                "position": 2,
                "medium": {
                    "release": {
                        "id": "a4c1dce4-0e16-483e-95de-aabff4378711",
                        "title": "Top 40 Hitdossier 1981-1982"
                    },
                    "position": 1,
                    "track_count": 20
                },
                "artists": [{
                    "id": "60d41417-feda-4734-bbbf-7dcc30e08a83",
                    "name": "Diana Ross"
                }, {
                    "id": "3cb25fb2-5547-4b05-adec-1a5e37830d46",
                    "name": "Lionel Richie"
                }],
                "title": "Endless Love"
            }],
            "id": "1fb13442-b0e7-4891-97de-255ba7e8730f"
        }, {
            "duration": 263,
            "tracks": [{
                "duration": 263,
                "position": 16,
                "medium": {
                    "release": {
                        "id": "add4c09f-b9f3-4e3f-b36b-22f30309ce2b",
                        "title": "Steve Wright's Sunday Love Songs, Volume 2"
                    },
                    "position": 1,
                    "track_count": 22,
                    "format": "CD"
                },
                "artists": [{
                    "id": "60d41417-feda-4734-bbbf-7dcc30e08a83",
                    "name": "Diana Ross"
                }, {
                    "id": "3cb25fb2-5547-4b05-adec-1a5e37830d46",
                    "name": "Lionel Richie"
                }],
                "title": "Endless Love"
            }],
            "id": "20df4da3-005e-4bde-9337-46925e709110"
        }, {
            "duration": 264,
            "tracks": [{
                "duration": 264,
                "position": 2,
                "medium": {
                    "release": {
                        "id": "d23d377b-b69a-424b-856c-b78dfde11feb",
                        "title": "Always And Forever (disc 1)"
                    },
                    "position": 1,
                    "track_count": 20,
                    "format": "CD"
                },
                "artists": [{
                    "id": "3cb25fb2-5547-4b05-adec-1a5e37830d46",
                    "name": "Lionel Richie"
                }],
                "title": "Endless Love"
            }],
            "id": "2cf76055-5a41-4a39-82ba-611b7142ab91"
        }, {
            "duration": 265,
            "tracks": [{
                "duration": 265,
                "position": 9,
                "medium": {
                    "release": {
                        "id": "3bc3d08b-7e50-47d0-951d-de95a10e1ee8",
                        "title": "The Love Album II"
                    },
                    "position": 1,
                    "track_count": 20,
                    "format": "CD"
                },
                "artists": [{
                    "id": "60d41417-feda-4734-bbbf-7dcc30e08a83",
                    "name": "Diana Ross"
                }, {
                    "id": "3cb25fb2-5547-4b05-adec-1a5e37830d46",
                    "name": "Lionel Richie"
                }],
                "title": "Endless Love"
            }],
            "id": "33f02920-5832-490d-bf5f-3cce793925bf"
        }....too big to display here..

请不要介意我在这里粘贴输出..

4

1 回答 1

2

python的文档中,

与 C 中一样,break 语句打破了最小的封闭 for 或 while 循环。

在你的情况下

for track in recording['tracks']:

尝试将代码放入函数中并使用 return:

def find_it(json, duration):
  for result in json['results']:
      for recording in result['recordings']:
          for track in recording['tracks']:
              track_artist = ''
              for artist in track['artists']:
                  try:
                      track_artist += repr(artist['name']) + ' '
                  except:
                      track_artist = ''
              #print str(track['duration']) + '-' + track['medium']['release']['title'] + '-' + track['title'] + '-' + track_artist
              if str(track['duration']) == str(duration):
                return track, track_artist
  return None, None

track, track_artist = find_it(json, duration)
print 'Matched:' + str(track['duration']) + '-' + track['medium']['release']['title'] + '-' + track['title'] + '-' + track_artist
于 2013-01-21T19:49:29.927 回答