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

如何使用PyDictionary获取单词单个释义并解决KeyError:1报错

问题解决方法

错误原因

dic.meaning()返回结果为嵌套字典结构,第一层键是词性字符串(如Noun、Verb),对应值是该词性下的释义列表,不支持直接用数字索引取第一层内容,因此会触发KeyError: 1报错。

实现代码

1. 导入依赖

首先导入需要的模块:

from PyDictionary import PyDictionary
import random

2. 基础调用与释义汇总

先获取单词释义并将所有释义展平为一维列表:

dic = PyDictionary()
meaning_dict = dic.meaning('book')

# 汇总所有词性下的全部释义
all_meanings = []
for pos_meanings in meaning_dict.values():
    all_meanings.extend(pos_meanings)

3. 取第一个释义

first_meaning = all_meanings[0]
print(first_meaning)

4. 随机选取单个释义(对应原始需求)

random_meaning = random.choice(all_meanings)
print(random_meaning)

可选:保留词性信息的随机取法

如果需要同时输出释义对应的词性,可使用以下写法:

# 随机选择词性
random_pos = random.choice(list(meaning_dict.keys()))
# 从该词性下随机选释义
random_meaning = random.choice(meaning_dict[random_pos])
print(f"[{random_pos}] {random_meaning}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:45:04