簡體   English   中英

Python如何擺脫PyDictionary錯誤消息

[英]Python how to get rid of PyDictionary error messages

我有以下代碼來檢查字詞中是否有單詞。 如果該單詞不存在,則對dictionary.meaning的調用將返回None。 問題是它還會發出錯誤消息“錯誤:發生以下錯誤:列表索引超出范圍”。 我做了一些研究,似乎我可以使用try:的組合,除了:但無論我嘗試了什么,仍然打印出錯誤信息。 這是一個顯示問題的測試用例。 如何在不顯示索引錯誤的情況下使此代碼正常工作?

碼:

    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)來使它沉默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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM