Replacing a word by randomly selected synonyms in a string?

927 views Asked by At

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?

1

There are 1 answers

0
Stefan Rendevski On BEST ANSWER

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