简体   繁体   中英

Python how to get rid of PyDictionary error messages

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?

Code:

    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")

Output:

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

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 putting the try/except around the section of code that would be erroring (the dictionary check in this case).

EDIT:

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

Second Edit: Using 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM