2014-01-10 110 views
0

在我的代码中,最后一个for循环决定是否匹配。如果有比赛,我想回到赛道冠军,如果有不匹配,我想回W¯¯用else语句返回值

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["tracks"]: 
       if value["name"] == track_title: 
        return track_title 
       else: 
        return w 

      return num_removed, json_dict, track_title, w 


num_words_removed, json_dict, track_title, w = decrementList(split_message) 

不幸的是,这不是我的理想的解决方案。我真的很想重新运行缩短的单词列表,直到有匹配的赛道。我尝试这样做:

for value in json_dict["tracks"]: 
    if value["name"] == track_title: 
     return track_title 
    else: 
     decrementList(w) 

但是,我得到了某种形式的无限循环和超时了我的请求。这在我的脑海中是有道理的。如果没有轨道匹配,请将缩短的列表以“w”存储并通过decrementList函数重新运行。

所以,我想我有两个问题。如何在else语句中返回两个值,以及如何才能重新运行缩短的列表,直到找到匹配的轨道。

回答

1

首先你需要考虑你想要返回的东西。看起来你并没有在这个问题上下定决心,因为有时候你返回一个值(track_titlew),有时候你会返回一个元组(num_removed, json_dict, track_title, w)。这我不能为你做,这取决于你以后需要什么。除此之外,我认为你应该使用一个生成器来产生结果,直到调用者满意为止(最好的第一个,然后降低匹配质量,即使用较少和较少的匹配词)。看看我的版本的代码:

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(w) 

      for track in json_dict["tracks"]: 
       if track["name"].lower().startswith(track_title.lower()): 
        yield num_removed, track, track["name"], w 

def quote(s): 
    return '"' + ('%r' % ("'"+s.encode('utf-8')))[2:] 

for num_words_removed, track, track_name, w in decrementList(split_message): 
    print '%2d %s by %s (track %d on %s from %s)' % (
    num_words_removed, 
    quote(track_name), 
    quote(track['artists'][0]['name']), 
    int(track['track-number']), 
    quote(track['album']['name']), 
    track['album']['released']) 
+0

你当然也可以删除行'如果值...'也得到不准确用缩短查询的措辞开始结果。这样你也可以得到“如果我不能把它带走”。 – Alfe

+0

嗨,谢谢你。几个部分混淆了我。我会看看虽然! – metersk