Python 来自 nltk.corpus 的 wordnet。如何使用 wordnet 获取几个句子中每个单词的定义?

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

我开始学习 wordnet,但示例中的所有内容都与特定单词相关联。如何使用 wordnet 获取多个句子中每个单词的定义?

我试过这样做:

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

但是:

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

我得到一个 list index out of range 错误,因为 wordnet.synsets('{w}') 方法返回了一个零长度 result.Without 检查这个,我尝试访问元素 [0],它不是当前的。您需要在尝试输出之前添加结果检查。

答案:

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