Wordnet synset - 奇怪的列表索引超出范围错误

Wordnet synset - strange list index out of range Error

我开始使用 nltk,我正在尝试生成一个函数,允许我传入一个形容词,从 wordnet 中提取第一个同义词集并将其与反义词一起打印出来。她是我的密码:

def placementOperator(wordItem):
   wordnet_lemmatizer = WordNetLemmatizer()
   placementItem = wordnet_lemmatizer.lemmatize(wordItem,'a')
   print("The placementItem is: " + placementItem)
   iterationSet = wn.synsets(placementItem, 'a')
   if iterationSet[0]:
       print(" This is the SS NAME : " + iterationSet[0].name())
       for j in iterationSet[0].lemmas():
           print("  This is the LEMMAAAA: " + j.name())
           if j.antonyms():
               print("   This is the RElATIONSHIP " + j.name(), j.antonyms()[0].name())
           else: print("    _______> NO ANTONYM!")
   else: pass

我快到了,只是我的解释器抛出了一个 'list out of range' 异常。我知道我不能调用不存在的列表位置,而且我知道当有人尝试这样做时会发生此错误。但是因为我正在使用 if iterationSet[0] 明确测试这个,所以我不确定我是如何以错误结束的。

如有任何建议,我们将不胜感激。

她是错误的:

Traceback (most recent call last):
  File "C:/Users/Admin/PycharmProjects/momely/associate/associate.py", line  57, in <module> preProcessor(0)
  File "C:/Users/Admin/PycharmProjects/momely/associate/associate.py", line 54, in preProcessor placementOperator(each_element[0])
   File "C:/Users/Admin/PycharmProjects/momely/associate/associate.py", line 31, in placementOperator if iterationSet[0]:
IndexError: list index out of range

很可能,wn.synsets(placementItem, 'a') 返回了一个空列表。如果 placementItem 不在 wordnet 中,就会发生这种情况。

因此,当您执行 iterationSet[0] 时,它会抛出超出范围的异常。相反,您可以将支票更改为:

if iterationSet:
    print( ....
    ....

而不是

if iterationSet[0]:
   print(...