Debug School

rakesh kumar
rakesh kumar

Posted on

Real Time Application of Nlp using Text Blob

Sentence Rewriting Using TextBlob

from textblob import TextBlob

def rewrite_sentence(text):
    blob = TextBlob(text)
    # Rewriting each sentence using synonyms (simplistic approach)
    rewritten_sentences = []
    for sentence in blob.sentences:
        words = sentence.words
        rewritten_words = []
        for word in words:
            synonyms = blob.synsets(word)
            if synonyms:
                # Use the first synonym if available
                rewritten_words.append(synonyms[0].lemmas()[0].name())
            else:
                rewritten_words.append(word)
        rewritten_sentences.append(" ".join(rewritten_words))
    return " ".join(rewritten_sentences)

# Test
text = "The quick brown fox jumps over the lazy dog."
rewritten_text = rewrite_sentence(text)
print("Original:", text)
print("Rewritten:", rewritten_text)
Enter fullscreen mode Exit fullscreen mode

Sentiment Analysis
Analyze the sentiment (polarity and subjectivity) of a text.


from textblob import TextBlob

def analyze_sentiment(text):
    blob = TextBlob(text)
    return blob.sentiment  # Polarity (-1 to 1) and Subjectivity (0 to 1)

# Input
text = "The movie was amazing and beautifully directed, but the ending was disappointing."
Enter fullscreen mode Exit fullscreen mode
# Output
print("Sentiment:", analyze_sentiment(text))
Enter fullscreen mode Exit fullscreen mode

Output:

Sentiment: Sentiment(polarity=0.35, subjectivity=0.75)
Enter fullscreen mode Exit fullscreen mode
  1. Language Detection Detect the language of the given text.
def detect_language(text):
    blob = TextBlob(text)
    return blob.detect_language()

# Input
text = "Bonjour tout le monde"
# Output
print("Detected Language:", detect_language(text))
Enter fullscreen mode Exit fullscreen mode

Output:

Detected Language: fr
Enter fullscreen mode Exit fullscreen mode
  1. Translation Translate text from one language to another (requires an active internet connection).
def translate_text(text, target_language):
    blob = TextBlob(text)
    return blob.translate(to=target_language)

# Input
text = "Hola, ¿cómo estás?"
# Output
print("Translated Text:", translate_text(text, "en"))
Enter fullscreen mode Exit fullscreen mode

Output:

Translated Text: Hello, how are you?

  1. Spelling Correction Automatically correct spelling mistakes in text.

def correct_spelling(text):
    blob = TextBlob(text)
    return blob.correct()

# Input
text = "I luv programing in Pyton."
# Output
print("Corrected Text:", correct_spelling(text))
Enter fullscreen mode Exit fullscreen mode

Output:

Corrected Text: I love programming in Python.
Enter fullscreen mode Exit fullscreen mode
  1. Word Tokenization Split text into individual words.
def tokenize_words(text):
    blob = TextBlob(text)
    return blob.words

# Input
text = "TextBlob makes natural language processing simple."
# Output
print("Tokenized Words:", tokenize_words(text))
Enter fullscreen mode Exit fullscreen mode

Output:

Tokenized Words: ['TextBlob', 'makes', 'natural', 'language', 'processing', 'simple']
Enter fullscreen mode Exit fullscreen mode
  1. Sentence Tokenization Split text into individual sentences.
def tokenize_sentences(text):
    blob = TextBlob(text)
    return blob.sentences

# Input
text = "TextBlob is amazing. It simplifies NLP tasks. You should try it!"
# Output
print("Tokenized Sentences:", tokenize_sentences(text))
Enter fullscreen mode Exit fullscreen mode

Output:

Tokenized Sentences: [Sentence("TextBlob is amazing."), Sentence("It simplifies NLP tasks."), Sentence("You should try it!")]
Enter fullscreen mode Exit fullscreen mode
  1. Part-of-Speech (POS) Tagging Tag each word with its grammatical part of speech.
def pos_tagging(text):
    blob = TextBlob(text)
    return blob.tags

# Input
text = "TextBlob is a Python library for processing textual data."
Enter fullscreen mode Exit fullscreen mode
# Output
print("POS Tags:", pos_tagging(text))
Enter fullscreen mode Exit fullscreen mode

Output:

POS Tags: [('TextBlob', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('Python', 'NNP'), ('library', 'NN'), ('for', 'IN'), ('processing', 'VBG'), ('textual', 'JJ'), ('data', 'NN')]
Enter fullscreen mode Exit fullscreen mode
  1. Noun Phrase Extraction Extract noun phrases from a text.
def extract_noun_phrases(text):
    blob = TextBlob(text)
    return blob.noun_phrases

# Input
text = "TextBlob is a powerful library for text processing and analysis."
# Output
print("Noun Phrases:", extract_noun_phrases(text))
Enter fullscreen mode Exit fullscreen mode

Output:

Noun Phrases: ['textblob', 'powerful library', 'text processing', 'analysis']
Enter fullscreen mode Exit fullscreen mode
  1. Word Frequency Analysis Count the frequency of each word in the text.

def word_frequency(text):
    blob = TextBlob(text)
    return blob.word_counts

# Input
text = "TextBlob is simple and TextBlob is powerful."
# Output
print("Word Frequencies:", word_frequency(text))
Enter fullscreen mode Exit fullscreen mode

Output:


Word Frequencies: {'textblob': 2, 'is': 2, 'simple': 1, 'and': 1, 'powerful': 1}
Enter fullscreen mode Exit fullscreen mode
  1. Synonym Replacement Replace words in a sentence with their synonyms.
from nltk.corpus import wordnet

def replace_with_synonyms(text):
    blob = TextBlob(text)
    words = blob.words
    synonyms = []
    for word in words:
        syns = wordnet.synsets(word)
        if syns:
            synonyms.append(syns[0].lemmas()[0].name())  # First synonym
        else:
            synonyms.append(word)
    return " ".join(synonyms)

# Input
text = "The quick brown fox jumps over the lazy dog."
# Output
print("Text with Synonyms:", replace_with_synonyms(text))
Enter fullscreen mode Exit fullscreen mode

Output:

Text with Synonyms: The quick brown fox jumps over the lazy dog
Pluralize Words
Automatically pluralize singular nouns in a sentence.

from textblob import TextBlob

def pluralize_words(text):
    blob = TextBlob(text)
    return " ".join([word.pluralize() if word.singularize() == word else word for word in blob.words])

# Input
text = "The cat jumps over the dog."
# Output
print("Pluralized Sentence:", pluralize_words(text))
Output:


Pluralized Sentence: The cats jumps over the dogs
Enter fullscreen mode Exit fullscreen mode
  1. Singularize Words Automatically convert plural nouns to their singular form.
def singularize_words(text):
    blob = TextBlob(text)
    return " ".join([word.singularize() if word.pluralize() == word else word for word in blob.words])

# Input
text = "The cats jump over the dogs."
# Output
print("Singularized Sentence:", singularize_words(text))
Output:

Singularized Sentence: The cat jump over the dog
Enter fullscreen mode Exit fullscreen mode
  1. Word Definitions Retrieve the definitions of words in a sentence.
from nltk.corpus import wordnet

def get_word_definitions(text):
    blob = TextBlob(text)
    definitions = {}
    for word in blob.words:
        synsets = wordnet.synsets(word)
        if synsets:
            definitions[word] = synsets[0].definition()
    return definitions

# Input
text = "The cat jumps over the lazy dog."
# Output
print("Word Definitions:", get_word_definitions(text))
Enter fullscreen mode Exit fullscreen mode

Output:

Word Definitions: {'cat': 'feline mammal usually having thick soft fur', 'jumps': 'the act of jumping; propelling yourself off the ground', 'dog': 'a member of the genus Canis'}
Enter fullscreen mode Exit fullscreen mode
  1. Word Lemmatization Convert words to their base form (lemma).
def lemmatize_words(text):
    blob = TextBlob(text)
    return " ".join([word.lemmatize() for word in blob.words])

# Input
text = "The leaves are falling off the trees."
# Output
print("Lemmatized Sentence:", lemmatize_words(text))
Output:

Lemmatized Sentence: The leaf are falling off the tree
Enter fullscreen mode Exit fullscreen mode
  1. Sentence Polarity Scoring Extract the polarity score of each sentence in a text.
def sentence_polarity(text):
    blob = TextBlob(text)
    return {str(sentence): sentence.sentiment.polarity for sentence in blob.sentences}

# Input
text = "I love this product. The delivery was terrible. Overall, it's okay."
# Output
print("Sentence Polarity:", sentence_polarity(text))
Output:


Sentence Polarity: {'I love this product.': 0.5, 'The delivery was terrible.': -1.0, "Overall, it's okay.": 0.0}
Enter fullscreen mode Exit fullscreen mode
  1. Word Similarity Find how similar two words are based on their meaning.
def word_similarity(word1, word2):
    synsets1 = wordnet.synsets(word1)
    synsets2 = wordnet.synsets(word2)
    if synsets1 and synsets2:
        return synsets1[0].wup_similarity(synsets2[0])  # Wu-Palmer similarity
    return None

# Input
word1, word2 = "cat", "dog"
# Output
print(f"Similarity between '{word1}' and '{word2}':", word_similarity(word1, word2))
Output:


Similarity between 'cat' and 'dog': 0.8571428571428571
Enter fullscreen mode Exit fullscreen mode
  1. Text Subjectivity Analysis Extract subjectivity scores of individual sentences.
def sentence_subjectivity(text):
    blob = TextBlob(text)
    return {str(sentence): sentence.sentiment.subjectivity for sentence in blob.sentences}

# Input
text = "I think this is the best idea ever. The weather is good."
# Output
print("Sentence Subjectivity:", sentence_subjectivity(text))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)