python-3.xreplacewordnetpattern-synonyms

Replacing a word by randomly selected synonyms in a string?


I have found the following code in Python that is doing the same work but it only replaces with manually selected synonym.

import nltk
from nltk.corpus import wordnet
synonyms = []
string="i love winter season"

for syn in wordnet.synsets("love"):
    for l in syn.lemmas():
        synonyms.append(l.name())
print(synonyms)     
rep=synonyms[2]     
st=string.replace("love",rep, 1)
print(st)

rep=synonyms[2] will be taking any synonym at index 2

What i want is to replace the selected word with its randomly selected synonym?


Solution

  • If I understand your question correctly, what you need is to select a random element from a list. This can be done in python like so:

    import random
    random.choice (synonyms)
    

    As answered here