You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Datamuse API生成JSON并取值,非空列表为何触发索引错误?

问题描述

我用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)

问题原因

  1. 空列表未做检查:不管是第一个单词的three_syllable_words还是第二个的two_syllable_words,你都直接调用random.choice,只要API返回的结果里没有符合条件的词,列表为空就会触发索引错误。哪怕是2个单词的场景,也可能因为输入词没有对应3音节相关词,或者第一个单词没有符合条件的押韵词,导致列表为空。
  2. 音节判断笔误:第二个单词的注释说要选2音节词,但代码里判断条件是num_syllables ==3,逻辑完全矛盾,就算有符合条件的词也会被过滤掉,直接导致列表为空。
  3. 参数逻辑冲突:第二个单词的lc参数设为first_word,这个参数的作用是找“常出现在该单词左侧的词”,比如lc="apple"会返回red这类词;同时你又要求rel_rhy(和first_word押韵),这两个条件叠加后几乎找不到符合要求的词,大概率会让列表为空。

修复方案

  1. 添加空列表检查:每次调用random.choice前,先判断列表是否为空,为空则提示用户更换输入或重试。
  2. 修正音节判断逻辑:如果要选2音节词,把第二个单词的判断条件改成num_syllables ==2。
  3. 调整参数逻辑:把lc参数改成最初用户输入的related_word(如果是要关联原输入词),或者直接去掉这个参数,避免条件冲突。

修复后的代码

import json, requests, random

# 第一个单词:获取和输入词相关的3音节词
related_word = input("word: ")
parameters = {
    'rel_trg': related_word,
    'md': 's'  # 请求音节数
}
response = requests.get('https://api.datamuse.com/words', params=parameters)
related = response.json()

three_syllable_words = []
for word in related:
    num_syllables = word.get('numSyllables', 0)
    if num_syllables == 3:
        three_syllable_words.append(word)

# 空列表检查
if not three_syllable_words:
    print("找不到符合条件的3音节相关词,请换个输入试试")
    exit()

first_word = random.choice(three_syllable_words)['word']

# 第二个单词:获取和第一个单词押韵的2音节词
parameters2 = {
    'rel_rhy': first_word,
    'lc': related_word,  # 修正为原输入词,避免条件冲突
    'md': 's'
}
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 == 2:  # 修正音节判断条件
        two_syllable_words.append(word)

# 空列表检查
if not two_syllable_words:
    print(f"找不到和{first_word}押韵的2音节词,请重试")
    exit()

second_word = random.choice(two_syllable_words)['word']
print(second_word, first_word)

内容的提问来源于stack exchange,提问作者user22657292

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 16:25:08