Sentiment Analysis with Python — Complete Project
In this tutorial, you'll learn about Sentiment Analysis with Python. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
What You'll Learn
Build a real-world sentiment analysis project — analyze text with multiple tools, visualize results, and expose your analysis through a web API.
Why It Matters
Sentiment analysis is the most common NLP task in industry. Companies use it to track brand perception, monitor customer support, and analyze product reviews.
Real-World Use
Analyzing customer reviews, monitoring social media mentions, and tracking sentiment in support tickets.
Method 1: VADER (Best for Social Media)
pip install vaderSentiment
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
text = "This product is absolutely amazing! I love it!"
scores = analyzer.polarity_scores(text)
print(scores)
Expected output:
{'neg': 0.0, 'neu': 0.261, 'pos': 0.739, 'compound': 0.939}
The compound score ranges from -1 (most negative) to +1 (most positive).
Method 2: TextBlob (Simple and Fast)
pip install textblob
from textblob import TextBlob
text = "The service was terrible. I'm very disappointed."
blob = TextBlob(text)
print(f"Polarity: {blob.sentiment.polarity}")
print(f"Subjectivity: {blob.sentiment.subjectivity}")
Method 3: Hugging Face (Most Accurate)
from transformers import pipeline
classifier = pipeline(
"sentiment-analysis",
model="distilbert-BASE-uncased-finetuned-sst-2-english"
)
reviews = [
"Best purchase I've ever made!",
"It's okay, nothing special.",
"Complete waste of money. Do not buy.]
]
for review in reviews:
result = classifier(review)[0]
print(f"{result['label']}: {result['score']:.3f} — {review}")
Build a Batch Analyzer
import csv
from textblob import TextBlob
def analyze_reviews(csv_file):
results = []
with open(csv_file) as f:
reader = csv.DictReader(f)
for row in reader:
blob = TextBlob(row["review"])
results.append({
"review": row["review"],
"polarity": blob.sentiment.polarity,
"sentiment": "positive" if blob.sentiment.polarity > 0
else "negative" if blob.sentiment.polarity < 0
else "neutral"
})
return results
reviews = analyze_reviews("reviews.csv")
positive = sum(1 for R in reviews if R["sentiment"] == "positive")
print(f"Positive: {positive}/{len(reviews)} ({positive/len(reviews)*100:.0f}%)")
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro