python - Python如何摆脱PyDictionary错误消息
问题描述
我有以下代码来检查字典中是否有单词。如果单词不存在,则对 dictionary.meaning 的调用返回 None。问题是它还吐出一条错误消息“错误:发生以下错误:列表索引超出范围”。我做了一些研究,看来我可以使用 try:, except: 的组合,但无论我尝试了什么,错误消息仍然会打印出来。这是一个显示问题的测试用例。如何在不显示索引错误的情况下使此代码工作?
代码:
def is_word(word):
from PyDictionary import PyDictionary
dictionary=PyDictionary()
rtn = (dictionary.meaning(word))
if rtn == None:
return(False)
else:
return (True)
my_list = ["no", "act", "amp", "xibber", "xyz"]
for word in my_list:
result = is_word(word)
if result == True:
print(word, "is in the dictionary")
else:
print(word, "is NOT in the dictionary")
输出:
no is in the dictionary
act is in the dictionary
amp is in the dictionary
Error: The Following Error occured: list index out of range
xibber is NOT in the dictionary
Error: The Following Error occured: list index out of range
xyz is NOT in the dictionary
解决方案
我猜你的 try/except 块是在错误的块周围,或者你没有正确地捕捉到它,但是如果没有你的代码就很难判断。
尝试将 try/except 放在可能出错的代码部分(在这种情况下是字典检查)。
编辑:
我的错。该错误正在由PyDictionary
库打印。您应该能够通过执行使其静音meaning(word, disable_errors=True)
。
def is_word(word):
from PyDictionary import PyDictionary
dictionary = PyDictionary()
try:
output = dictionary.meaning(word, disable_errors=True)
except:
return False
else:
return bool(output)
my_list = ["no", "act", "amp", "xibber", "xyz"]
for word in my_list:
result = is_word(word)
if result:
print("{} is in the dictionary".format(word))
else:
print("{} is NOT in the dictionary".format(word))
第二次编辑:使用https://github.com/tasdikrahman/vocabulary。
from vocabulary.vocabulary import Vocabulary
vb = Vocabulary()
my_list = ["no", "act", "amp", "xibber", "xyz"]
for word in my_list:
if vb.meaning(word):
print("{} is in the dictionary".format(word))
else:
print("{} is NOT in the dictionary".format(word))
推荐阅读
- mysql - 为什么输出值重复?什么应该是正确的查询?
- mysql - 我想用 DESC 对某个字段进行 ORDER BY
- matlab - 是否可以将优化中计算的值控制为有限值?
- python - python 正则表达式在元素处拆分字符串并提取链接+文本
- command-line - 2>&1 在命令行中会做什么
- weblogic - 使用 WLST 脚本暂停/恢复部署在 Weblogic 12c 中的 MDB
- c# - 如何通过单击按钮从另一个窗口的控制中保存图像?
- amazon-web-services - 如何在 aws 中聚合来自多个 lambda 的数据
- sap - 使用 Project Piper 进行自动化测试
- react-native-android - 如何在 react-native 中将 base64 代码发送到我的网络服务?