Here we have created what some may call a start to a text spinner, the following will find and replace adjectives with a synonym. To achieve this, we are using the Python NLTK (natural language toolkit) which is a Python package for natural language processing (NLP).
We begin by marking the words in the sentence provided via user input, this is done through POS tagging (Part of speech tagging). This will tag each word with a label based on its definition and context.
Some example tags can be found below:
- NN is the POS tag for nouns.
- RB is the POS tag for adverbs.
- JJ is the POS tag for adjectives.
As part of this project, we are interested in adjectives only, the corresponding tag for this is “JJ”. This project will take input from the user and assign to each word the corresponding POS tag, we then narrow them down to the “JJ” tag only – marking out our adjectives.
For each adjective found, we then look up the word using the sysnets() method to retrieve a set of synonyms that share a common meaning. Using the lemma() method we can then retrieve the number of synonyms of the sysnset. These are then appended to a list where we pick and select one at random and then replace it with what already exists.
Full source code for this project seen below:
import nltk from nltk.corpus import wordnet import random syn = list() while True: sentence = input("Enter Sentence : ") tags = nltk.pos_tag(sentence.split(' ')) adjectives = [w for w, t in tags if t == 'JJ'] for each in adjectives: for synset in wordnet.synsets(each): for lemma in synset.lemmas(): syn.append(lemma.name()) syn = list(set(syn)) Spin =(random.choice(syn)) sentence = sentence.replace(each, Spin) print(sentence) syn = list()
Simple examples for this project were:
- “My house is massive” changed to “my house is monumental”
- “That house is scary” changed to “That house is chilling”
- “I was angry” changed to “I was raging”