Mike Nedelko
Mike Nedelko

Reputation: 709

Wordnet synset - strange list index out of range Error

I started working with nltk and I am attempting to generate a function that would allow me to pass in an adjective, extract the first synset from wordnet and print it alongside its antonym. Her is my code:

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

I am almost there, except that my interpreter throws a 'list out of range' exception. I know that I can't call a list position that doesn't exist and I know that this error occurs when one tries to do so. But since I am explicitly testing for this with if iterationSet[0] I am not sure how I am ending up with the error anyways.

Any advice would be highly appreciated.

Her is the error:

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

Upvotes: 0

Views: 1182

Answers (1)

kanghj91
kanghj91

Reputation: 140

Most likely, wn.synsets(placementItem, 'a') returned you an empty list. This can happen if placementItem isn't in wordnet.

Therefore, when you did iterationSet[0], it throws an out of range exception. Instead, you can change your check to be :

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

instead of

if iterationSet[0]:
   print(...

Upvotes: 1

Related Questions