🧠 AI with Python – 📈 Sentiment Analysis with TextBlob
Posted On: September 2, 2025
Description:
Understanding how people feel from text — whether it’s a review, comment, or email — is a common requirement in real projects. TextBlob offers a very quick way to get a sentiment score without heavy setup or large models.
Why TextBlob?
- Simple API: Access sentiment with TextBlob(text).sentiment.
- Fast baseline: Great for quick experiments or dashboards.
- Readable outputs: Two numbers — polarity (−1 to 1) and subjectivity (0 to 1).
Installing the Package
pip install textblob
If you encounter lookup errors for corpora, run:
python -m textblob.download_corpora
Minimal Implementation
Compute sentiment for a single sentence:
from textblob import TextBlob
text = "I absolutely love how simple TextBlob makes sentiment analysis!"
pol, sub = TextBlob(text).sentiment.polarity, TextBlob(text).sentiment.subjectivity
Map polarity to a simple label:
def polarity_to_label(p, eps=0.05):
return "Positive" if p > eps else "Negative" if p < -eps else "Neutral"
Sample Output
For the input:
"I absolutely love how simple TextBlob makes sentiment analysis!"
You might get:
Polarity: 0.625, Subjectivity: 0.700 → Label: Positive
Key Takeaways
- Polarity tells you how negative/positive a sentence is.
- Subjectivity indicates how opinionated the text is.
- Quick, lightweight baseline for comments, reviews, and feedback.
Limitations
- Not robust to sarcasm, irony, or complex context.
- May underperform on domain-specific jargon (e.g., finance, medicine).
- For multi-language support or higher accuracy, consider model-based approaches (e.g., Transformers pipelines).
Code Snippet:
# Install TextBlob (run in a notebook cell or terminal)
# !pip install textblob
# Optional: download corpora used by TextBlob (only if you see lookup errors)
# !python -m textblob.download_corpora
from textblob import TextBlob
# Sample inputs
single_sentence = "I absolutely love how simple TextBlob makes sentiment analysis!"
texts = [
"The movie was fantastic and truly inspiring.",
"It was okay, nothing special.",
"This is the worst service I have ever experienced."
]
# Create a TextBlob and read sentiment
blob = TextBlob(single_sentence)
polarity = blob.sentiment.polarity # how positive/negative
subjectivity = blob.sentiment.subjectivity # how subjective/objective
print("Sentence:", single_sentence)
print("Polarity:", round(polarity, 3))
print("Subjectivity:", round(subjectivity, 3))
def polarity_to_label(p, eps=0.05):
"""
Map polarity score to a label:
- p > +eps → 'Positive'
- p < -eps → 'Negative'
- otherwise → 'Neutral'
"""
if p > eps:
return "Positive"
if p < -eps:
return "Negative"
return "Neutral"
for t in texts:
p = TextBlob(t).sentiment.polarity
s = TextBlob(t).sentiment.subjectivity
print(f"\nText: {t}")
print(f"Polarity: {p:.3f} | Subjectivity: {s:.3f} | Label: {polarity_to_label(p)}")
Link copied!
Comments
Add Your Comment
Comment Added!
No comments yet. Be the first to comment!