Search code examples
pythonnltkwordnet

Python wordnet from nltk.corpus. How can I get the definition of each word in several sentences using wordnet?


I started learning wordnet, but everything in the examples is tied to a specific word. How can I get the definition of each word in several sentences using wordnet?

I tried to do something like this:

from nltk.corpus import wordnet
from nltk.tokenize import word_tokenize

words = []
synt = "My friends have come too late."
words = word_tokenize(synt)

for w in words:
word = wordnet.synsets('{w}')[0]
print("Synset name : ", word.name())
# Defining the word
print("\nSynset meaning : ", word.definition())
# list of phrases that use the word in context
print("\nSynset example : ", word.examples())

but:

Traceback (most recent call last):
  File "C:/projects/WordNet/test.py", line 10, in <module>
    word = wordnet.synsets('{w}')[0]
IndexError: list index out of range

Process finished with exit code 1

Solution

  • I got a list index out of range error because the wordnet.synsets('{w}') method returned a zero-length result.Without checking this, I try to access the element [0], which is not present. You need to add a result check before trying to output it.

    Answer:

    from nltk.corpus import wordnet
    
    synt = "My friends have come too late."
    words = synt.split(' ')
    
    for word in words:
    result = wordnet.synsets(word)
        if not result:
            print('No found: ', word)
            continue
    
        for item in result:
            print("Synset name: ", item.name())
            print("Synset meaning: ", item.definition())
            print("Synset example: ", item.examples())