2014-01-10 58 views
2
import requests 
import json 

# initial message 
message = "if i can\'t let it go out of my mind" 

# split into list 
split_message = message.split() 

def decrementList(words): 
    for w in [words] + [words[:-x] for x in range(1,len(words))]: 
     url = 'http://ws.spotify.com/search/1/track.json?q=' 
     request = requests.get(url + "%20".join(w)) 

     json_dict = json.loads(request.content) 
     num_results = json_dict['info']['num_results'] 
     if num_results > 0: 
      num_removed = len(words) - len(w) 

      #track_title = ' '.join(words) 

      track_title = "If I Can't Take It with Me" 

      for value in json_dict.items(): 
       if value == track_title: 
        print "match found" 

      return num_removed, json_dict 


num_words_removed, json_dict = decrementList(split_message) 

在下面的代碼中,我試圖將歌曲的名稱與我的搜索查詢進行匹配。在這個特定的查詢中,歌曲不匹配,但我添加了一個與返回的查詢的歌曲匹配的變量。函數末尾的for循環應該與軌道標題變量匹配,但我無法弄清楚爲什麼它不起作用。有沒有簡單的方法來找到已知鍵的所有值?在這種情況下,關鍵是「名稱」如何查找python中特定鍵的值

回答

2

您必須在tracks字典中搜索曲目標題。因此,只要改變像你這個代碼

for value in json_dict["tracks"]: 
    if value["name"] == track_title: 

將打印

match found 
相關問題