在下面的代码中,我将使用split_message列表并查询API。如果没有结果,我的下一步是将列表的索引递减-1,所以我从列表中删除最后一项并重试搜索。如果再没有结果,我想重复这个过程,直到收到结果。
import requests
import json
message = "if i can\'t let it go out of my mind"
split_message = message.split()
length = len(split_message)
def decrementList():
initial_request = requests.get('http://ws.spotify.com/search/1/track.json?q='+"%20"
.join(split_message[:]))
json_string = initial_request.content
json_dict = json.loads(json_string)
num_results = json_dict['info']['num_results']
if num_results == 0:
print "Sorry, no match!"
if num_results > 0:
print "Result found!"
decrementList()
实际上,我的下一步是采取这个:
requests.get('http://ws.spotify.com/search/1/track.json?q='+"%20"
.join(split_message[:]))
并将其转换为:
requests.get('http://ws.spotify.com/search/1/track.json?q='+"%20"
.join(split_message[:-1]))
然后这个:
requests.get('http://ws.spotify.com/search/1/track.json?q='+"%20"
.join(split_message[:-2]))
重复直到我得到一场比赛。
我可以想到非常非pythonic的方法来做到这一点,但如果声明似乎太多了。那么对于我想要实现的目标,什么是最好和最pythonic的解决方案呢?
答案 0 :(得分:1)
使用list.pop
:
>>> message = "if i can\'t let it go out of my mind"
>>> split_message = message.split()
>>> split_message.pop()
'mind'
>>> split_message
['if', 'i', "can't", 'let', 'it', 'go', 'out', 'of', 'my']
>>> split_message.pop()
'my'
>>> split_message
['if', 'i', "can't", 'let', 'it', 'go', 'out', 'of']
答案 1 :(得分:1)
修改强>
实际上,我更喜欢这个版本。有点清洁恕我直言。
def decrementList(words):
words_remaining = words[:]
while words_remaining:
url = 'http://ws.spotify.com/search/1/track.json?q='
request = requests.get(url + '%20'.join(words_remaining))
json_dict = json.loads(request.content)
if json_dict['info']['num_results'] > 0:
num_words_taken = len(words) - len(words_remaining)
return num_words_taken, json_dict
words_remaining.pop()
从@falsetru获得list.pop
灵感,请参阅其他答案。
原始回答
也许这更符合你的喜好:
import requests
import json
message = "if i can\'t let it go out of my mind"
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)
return num_removed, json_dict
num_words_removed, json_dict = decrementList(split_message)
关键是[words] + [words[:-x] for x in range(1,len(words))]
。假设words = message.split()
,您将获得列表
[
['if', 'i', 'can', 'let', 'it', 'go', 'out', 'of', 'my', 'mind'],
['if', 'i', 'can', 'let', 'it', 'go', 'out', 'of', 'my'],
['if', 'i', 'can', 'let', 'it', 'go', 'out', 'of'],
['if', 'i', 'can', 'let', 'it', 'go', 'out'],
['if', 'i', 'can', 'let', 'it', 'go'],
['if', 'i', 'can', 'let', 'it'],
['if', 'i', 'can', 'let'],
['if', 'i', 'can'],
['if', 'i'],
['if']
]
我相信你做的是你想要的,它可以说是'Pythonic'。一旦得到想要的结果,该功能就会突破循环。它返回您必须从列表中删除的单词数以获得一些结果,以及请求产生的JSON字典。