在尝试从datamuse API中生成一个具有特定音节数的单词列表,并随机选择其中一个单词进行打印时,我经常收到索引错误,而我知道列表不可能是空的。每个后续单词都依赖于与前一个单词有关的参数。我的完整代码有7个字,但基本上都是第二个字的副本。对于所有7个单词,是的,列表有时会是空的,但在只有2个单词和给定参数的情况下,我不明白为什么会发生这种情况。
`import json, requests, random
# FIRST WORD
related_word = input("word: ")
#create list for related words
parameters = {
'rel_trg': related_word,
'md': 's' # Request the number of syllables for each word
}
response = requests.get('https://api.datamuse.com/words', params=parameters)
related = response.json()
three_syllable_words = [] # creates list for three syllable words
for word in related:
num_syllables = word.get('numSyllables', 0)
if num_syllables == 3: #filters list to only 3 syllable words
three_syllable_words.append(word)
#select random three_syllable_word
first_three_sylword = random.choice(three_syllable_words)
first_word = first_three_sylword['word'] #use only word data
#print(first_word)
# Second Word
parameters2 = {
'rel_rhy':first_word, # Rhymes
'lc':first_word, # Left context to the original word entered by the user
'md': 's' # Request the number of syllables for each word
}
response2 = requests.get('https://api.datamuse.com/words', params=parameters2)
lcrhyme = response2.json()
two_syllable_words = []
for word in lcrhyme:
num_syllables = word.get('numSyllables', 0)
if num_syllables == 3:
two_syllable_words.append(word)
first_two_syl_word = random.choice((two_syllable_words))
second_word = first_two_syl_word['word']
print(second_word, first_word)`
2条答案
按热度按时间kiayqfof1#
我经常收到一个索引错误,而我知道列表不可能是空的。
你为什么这么想?
如果
related
是空的,你认为会发生什么?尝试
x6492ojm2#
正如@ david在answer here中指出的那样,问题是有时API无法为给定的单词找到“相关”或“押韵”的单词。在这些情况下,对
random.choice()
的调用会传递一个空列表,这将抛出您看到的错误。你需要防范这些情况。比如:
以下是我最初可能会如何处理这项任务:
这可能会给你一个给予的结果,如: