Random Synonym Generator

  • Share this:

Code introduction


This function takes a word as input and returns a random synonym for that word.


Technology Stack : nltk.corpus.wordnet, nltk.tokenize.word_tokenize, nltk.stem.WordNetLemmatizer

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from nltk.corpus import wordnet
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer

def get_random_synonyms(word):
    # Tokenize the input word
    tokens = word_tokenize(word)
    # Initialize the lemmatizer
    lemmatizer = WordNetLemmatizer()
    # Lemmatize the input word
    lemma = lemmatizer.lemmatize(tokens[0], 'n')
    # Get synonyms for the lemma
    synonyms = wordnet.synsets(lemma)
    # Randomly select a synonym
    random_synonym = random.choice(synonyms).lemmas()[0].name()
    return random_synonym