使用API创建json并从列表中打印,为什么我得到索引错误时,列表不是空的

lawou6xi  于 2023-10-21  发布在  其他
关注(0)|答案(2)|浏览(124)

在尝试从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)`
kiayqfof

kiayqfof1#

我经常收到一个索引错误,而我知道列表不可能是空的。
你为什么这么想?

response = requests.get('https://api.datamuse.com/words', params=parameters)
related = response.json()

print(related)

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)

如果related是空的,你认为会发生什么?
尝试

random.choice([])
x6492ojm

x6492ojm2#

正如@ david在answer here中指出的那样,问题是有时API无法为给定的单词找到“相关”或“押韵”的单词。在这些情况下,对random.choice()的调用会传递一个空列表,这将抛出您看到的错误。
你需要防范这些情况。比如:

word  = random.choice(words)["word"] if words else ""

以下是我最初可能会如何处理这项任务:

import random
import requests

def get_related_rhyme(word, related_syllables=3, rhyme_syllables=2):
    related_word = get_related_word(word, related_syllables)
    related_rhyme = get_rhyming_word(related_word, rhyme_syllables)
    return (related_word, related_rhyme)

def get_related_word(word, syllables):
    if not word or not syllables:
        return ""

    url = "https://api.datamuse.com/words"
    parameters = {"rel_trg": word, "md": "s"}
    response = requests.get(url, params=parameters)
    words = response.json()
    return get_random_word(words, syllables)

def get_rhyming_word(word, syllables):
    if not word or not syllables:
        return ""

    url = "https://api.datamuse.com/words"
    parameters = {"rel_rhy":word, "lc":word, "md": "s"}
    response = requests.get(url, params=parameters)
    words = response.json()
    return get_random_word(words, syllables)

def get_random_word(words, syllables):
    syllable_words = [
        word
        for word
        in words
        if word.get("numSyllables", 0) == syllables
    ]
    return random.choice(syllable_words)["word"] if syllable_words else ""

TEMPLATE = '''word: "{w}", related: "{rw}", related rhyme: "{rr}"'''

word = "parkinglot"
related_word, related_rhyme = get_related_rhyme(word)
print(TEMPLATE.format(w=word, rw=related_word, rr=related_rhyme))

word = "apartment"
related_word, related_rhyme = get_related_rhyme(word)
print(TEMPLATE.format(w=word, rw=related_word, rr=related_rhyme))

这可能会给你一个给予的结果,如:

word: "parkinglot", related: "", related rhyme: ""
word: "apartment", related: "manhattan", related rhyme: "patin"

相关问题