To find synonyms, definitions and example sentences using WordNet

▼魔方 西西 提交于 2019-12-02 16:00:06
def synset(word):
    wn.synsets(word)

doesn't return anything so by default you get None

you should write

def synset(word):
    return wn.synsets(word)

Extracting lemma names:

from nltk.corpus import wordnet
syns = wordnet.synsets('car')
syns[0].lemmas[0].name
>>> 'car'
[s.lemmas[0].name for s in syns]
>>> ['car', 'car', 'car', 'car', 'cable_car']


[l.name for s in syns for l in s.lemmas]
>>>['car', 'auto', 'automobile', 'machine', 'motorcar', 'car', 'railcar', 'railway_car', 'railroad_car', 'car', 'gondola', 'car', 'elevator_car', 'cable_car', 'car']

Here I have created a module which can easily be used(imported), and with a string being passed to it, will return all the lemma words of the string.

Module:

#!/usr/bin/python2.7
''' pass a string to this funciton ( eg 'car') and it will give you a list of
words which is related to cat, called lemma of CAT. '''
from nltk.corpus import wordnet as wn
import sys
#print all the synset element of an element
def lemmalist(str):
    syn_set = []
    for synset in wn.synsets(str):
        for item in synset.lemma_names:
            syn_set.append(item)
    return syn_set

Usage:

Note: module name is lemma.py hence "from lemma import lemmalist"

>>> from lemma import lemmalist
>>> lemmalist('car')
['car', 'auto', 'automobile', 'machine', 'motorcar', 'car', 'railcar', 'railway_car', 'railroad_car', 'car', 'gondola', 'car', 'elevator_car', 'cable_car', 'car']

Cheers!

synonyms = []
for syn in wordnet.synsets("car"):
    for l in syn.lemmas():
        synonyms.append(l.name())
print synonyms

In NLTK 3.0, lemma_names has been changed from attribute to method. So if you get an error saying:

TypeError: 'method' object is not iterable

You can fix it using:

>>> from nltk.corpus import wordnet as wn
>>> [item for sysnet in wn.synsets('car') for item in sysnet.lemma_names()]

This will output:

>>> [
       'car', 'auto', 'automobile', 'machine', 'motorcar', 'car', 
       'railcar', 'railway_car', 'railroad_car', 'car', 'gondola', 
       'car', 'elevator_car', 'cable_car', 'car'
    ]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!