【问题标题】:How to get all the hyponyms of a word/synset in python nltk and wordnet?如何在 python nltk 和 wordnet 中获取单词/同义词的所有下位词?
【发布时间】:2013-02-26 03:58:25
【问题描述】:

我有一个 wordnet 中所有名词的列表,现在我想只留下作为车辆的单词并删除其余的单词。我该怎么做?下面是我想做的伪代码,但我不知道如何让它工作

for word in wordlist:
  if not "vehicle" in wn.synsets(word):
    wordlist.remove(word)

【问题讨论】:

    标签: python nltk wordnet


    【解决方案1】:
    from nltk.corpus import wordnet as wn
    vehicle = wn.synset('vehicle.n.01')
    typesOfVehicles = list(set([w for s in vehicle.closure(lambda s:s.hyponyms()) for w in s.lemma_names()]))
    

    这将为您提供来自每个同义词集中的所有唯一词,这些词是名词“车辆”(第一种意义)的 hyponym。

    【讨论】:

    • 但是当我尝试进一步缩小范围时,我得到了这个错误 Traceback (most recent call last): File "D:...\test.py", line 10, in if单词中的“汽车”:TypeError:“Synset”类型的参数不可迭代
    • @Jared,非常优雅的答案,但是当Synset.closure(lambda s:s.hyponyms() 进入无限循环时,会有一个gotcha。试试wn.synset('restrain.v.01').closure(lambda s:s.hyponyms()
    • 我用这个方法得到TypeError: 'method' object is not iterable。
    • @StefanD 这是一个相对较旧的答案,可能不适用于较新版本的 NLTK。如果您找到适用于较新版本的替代解决方案,请发布答案或随时更新此答案!
    • 用户 Easton 在回答中评论说 lemma_names 是一种方法,因此应该添加括号。不知道这是否正确,但我将其留在这里供熟悉此模块的人查看。
    【解决方案2】:
    def get_hyponyms(synset):
        hyponyms = set()
        for hyponym in synset.hyponyms():
            hyponyms |= set(get_hyponyms(hyponym))
        return hyponyms | set(synset.hyponyms())
    

    【讨论】:

    • 这对 NLTK 3.0.3 非常有效,不像 jared' 答案(TypeError: 'method' object is not iterable),谢谢!
    猜你喜欢
    • 2013-10-16
    • 1970-01-01
    • 2016-11-09
    • 2014-08-31
    • 2023-03-11
    • 1970-01-01
    • 2017-04-18
    • 2015-09-22
    • 1970-01-01
    相关资源
    最近更新 更多