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语句中返回两个值,以及如何才能重新运行缩短的列表,直到找到匹配的轨道。
你当然也可以删除行'如果值...'也得到不准确用缩短查询的措辞开始结果。这样你也可以得到“如果我不能把它带走”。 – Alfe
嗨,谢谢你。几个部分混淆了我。我会看看虽然! – metersk