2 min read

Sentiment Analysis with TextBlob

This guide demonstrates how to perform simple sentiment analysis on text using the TextBlob library. TextBlob provides a simple API for diving into common natural language processing (NLP) tasks.

Modules Used:

  • textblob: For processing textual data.
  • argparse: To handle command-line arguments.

Installation

pip install textblob
python -m textblob.download_corpora

The Code

Save this as sentiment.py.

from textblob import TextBlob
import argparse

def analyze_sentiment(text):
    print(f"Analyzing: \"{text}\"\n")

    blob = TextBlob(text)

    # Polarity: Float within the range [-1.0, 1.0]
    # -1.0 is very negative, 1.0 is very positive
    polarity = blob.sentiment.polarity

    # Subjectivity: Float within the range [0.0, 1.0]
    # 0.0 is very objective, 1.0 is very subjective
    subjectivity = blob.sentiment.subjectivity

    print(f"Polarity:     {polarity:.2f}", end=" ")
    if polarity > 0.1:
        print("(Positive)")
    elif polarity < -0.1:
        print("(Negative)")
    else:
        print("(Neutral)")

    print(f"Subjectivity: {subjectivity:.2f}", end=" ")
    if subjectivity > 0.5:
        print("(Subjective/Opinion)")
    else:
        print("(Objective/Fact)")

    # Sentence-level analysis
    if len(blob.sentences) > 1:
        print("\nSentence Breakdown:")
        for sentence in blob.sentences:
            print(f"  - \"{sentence}\" (Polarity: {sentence.sentiment.polarity:.2f})")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="TextBlob Sentiment Analyzer")
    parser.add_argument("text", help="Text to analyze")

    args = parser.parse_args()

    analyze_sentiment(args.text)

Usage

# Analyze a simple sentence
python sentiment.py "I love programming in Python. It is amazing."

# Analyze a negative sentence
python sentiment.py "This is the worst experience I have ever had."

programming/python/python