简体   繁体   中英

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

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

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

I got a list index out of range error because the wor.net.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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM