我开始学习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}')
方法返回的长度为零。如果不检查此内容,我将尝试访问不存在的元素[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())