To make synonym word change in Python, we can use the nltk
library. Here are the steps to follow:
- Install
nltk
library by running!pip install nltk
in your Python environment. - Import the necessary modules:
import nltk from nltk.corpus import wordnet
- Define a function that takes a word as input and returns a synonym of that word: This function first gets all the synsets (sets of synonyms) of the input word from WordNet, and then returns the first lemma (synonym) of the first synset. If there are no synsets for the word, the function returns the input word itself.
def get_synonym(word): synonyms = [] for syn in wordnet.synsets(word): for lemma in syn.lemmas(): synonyms.append(lemma.name()) if len(synonyms) > 0: return synonyms[0] else: return word
- Test the function by calling it with a word: This should output a synonym of the word “happy”.
word = "happy" print(get_synonym(word))
Here’s the full code:
import nltk
from nltk.corpus import wordnet
def get_synonym(word):
synonyms = []
for syn in wordnet.synsets(word):
for lemma in syn.lemmas():
synonyms.append(lemma.name())
if len(synonyms) > 0:
return synonyms[0]
else:
return word
word = "happy"
print(get_synonym(word))
Output: felicitous