【问题标题】:Python wordnet from nltk.corpus. How can I get the definition of each word in several sentences using wordnet?来自 nltk.corpus 的 Python wordnet。如何使用 wordnet 获得几个句子中每个单词的定义?
【发布时间】:2020-06-09 16:28:22
【问题描述】:

我开始学习 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

【问题讨论】:

    标签: python nltk wordnet


    【解决方案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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      相关资源
      最近更新 更多