Python如何摆脱PyDictionary错误消息 [英] Python how to get rid of PyDictionary error messages
问题描述
我有以下代码来检查字典中是否有单词.如果该词不存在,则对dictionary.意义的调用将返回None.问题在于它还会吐出一条错误消息错误:发生以下错误:列表索引超出范围".我做了一些研究,看来我可以使用try:的组合,但:但是:无论我尝试了什么,错误消息仍然会打印出来.这是显示问题的测试用例.如何在不显示索引错误的情况下使此代码正常工作?
I have the following code to check if a word is in the dictionary. If the word does not exist the call to dictionary.meaning returns None. The problem is that it also spits out an error message "Error: The Following Error occured: list index out of range". I did some research and it appeared that I could use a combination of try:, except: but no matter what I tried the error message is still printed out. Here is a test case that shows the problem. How can I make this code work without displaying the index error?
代码:
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块位于错误的块周围,或者您没有正确捕获它,但是如果没有代码,很难分辨出来.
I'm guessing your try/except block was around the wrong block, or you weren't catching it properly, but it's tough to tell without your code.
尝试将try/except放在可能出错的代码部分(在这种情况下为字典检查).
Try putting the try/except around the section of code that would be erroring (the dictionary check in this case).
我的错误.错误已由 PyDictionary
库.您应该可以通过执行意义(单词,disable_errors = True)
使它静音.
My mistake. The error is getting printed by the PyDictionary
library. You should be able to silence it by doing 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))
这篇关于Python如何摆脱PyDictionary错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!