Python如何摆脱PyDictionary错误消息

时间:2018-09-28 23:51:01

标签: python python-3.x dictionary

我有以下代码来检查字典中是否有单词。如果该词不存在,则对dictionary。意义的调用将返回None。问题在于它还会吐出一条错误消息“错误:发生以下错误:列表索引超出范围”。我做了一些研究,看来我可以使用try:的组合,但:但是:无论我尝试了什么,错误消息仍然会打印出来。这是显示问题的测试用例。如何在不显示索引错误的情况下使此代码正常工作?

代码:

def Scraper(x):
#setup
query = x
query = query.decode('utf-8')
searchUrl = 'https://www.google.co.jp/search?q=' + query

urls = []

html = requests.get(searchUrl).text
bs = BeautifulSoup(html, 'html5lib')

输出:

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

1 个答案:

答案 0 :(得分:3)

我猜您的try / except块位于错误的块周围,或者您无法正确捕获它,但是如果没有代码,很难分辨出来。

尝试将try / except放在可能出错的代码部分(在这种情况下为字典检查)。

编辑:

我的错误。 PyDictionary library将打印错误。您应该可以通过执行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))