Search code examples
stringlistnltkwordnetsynonym

How to find a synonyms in a list of strings using NLTK synsets?


I have a list of strings :

words1 =  ['feds', 'move', 'to', 'require', 'cartocar', 'safety', 'communication']

I want to find a synsets for each of that words using NLTK wordnet synsets. Firstly, I use one string in my list. Here's my codes :

from nltk.corpus import wordnet as wn

word = ['feds']

data1 = ' '.join(word)

def getSynonyms(data1):
    synonymList1 = []
    wordnetSynset1 = wn.synsets(data1)

    for synset1 in wordnetSynset1:
        for synWords1 in synset1.lemma_names():
            synonymList1.append(synWords1)
    print synonymList1

print "list of synonyms : ", getSynonyms(data1)

and it works. Here's the result :

list of synonyms :  [u'Federal', u'Fed', u'federal_official', u'Federal_Reserve_System', u'Federal_Reserve', u'Fed', u'FRS']

but when I use a list of strings "words1", it doesn't works and the output is none like this >> [].

anyone can help? thanks


Solution

  • You need to pass the words individually and not after joining them.

    from nltk.corpus import wordnet as wn
    
    
    def getSynonyms(word1):
            synonymList1 = []
            for data1 in word1:
                  wordnetSynset1 = wn.synsets(data1)
                  tempList1=[]
                  for synset1 in wordnetSynset1:
                     for synWords1 in synset1.lemma_names():
                         tempList1.append(synWords1)
                  synonymList1.append(tempList1)
            return synonymList1
    
    
    word1 =  ['feds', 'move', 'to', 'require', 'cartocar', 'safety', 'communication']
    print getSynonyms(word1)