Sentiment Analysis in NLP

Sentiment Analysis, also called opinion mining, is the computational study of opinions, sentiments, and emotions expressed in text. It is widely used in understanding customer feedback, social media, and market research.

Types of Sentiment Analysis

Popular Techniques

10 Examples of Sentiment Analysis

Example 1: Simple Polarity Detection using TextBlob


from textblob import TextBlob

text = "I love this product! It works wonderfully."
blob = TextBlob(text)
print("Polarity:", blob.sentiment.polarity)
print("Subjectivity:", blob.sentiment.subjectivity)

Example 2: Using VADER for Social Media Text


from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

analyzer = SentimentIntensityAnalyzer()
scores = analyzer.polarity_scores(text)
print("VADER Scores:", scores)

Example 3: Sentiment Classification with Hugging Face Transformers


from transformers import pipeline

sentiment_pipeline = pipeline("sentiment-analysis")
result = sentiment_pipeline(text)
print("Transformers Result:", result)

Example 4: Aspect-Based Sentiment Extraction


sentence = "The camera quality is great but the battery life is terrible."
aspects = {
    "camera": "great",
    "battery": "terrible"
}
for aspect, opinion in aspects.items():
    sentiment = TextBlob(opinion).sentiment.polarity
    print(f"{aspect} sentiment: {'positive' if sentiment > 0 else 'negative'}")

Example 5: Training a Custom Sentiment Classifier


from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

train_texts = ["I love this", "I hate that", "It's amazing", "It's terrible"]
train_labels = ["pos", "neg", "pos", "neg"]

vectorizer = CountVectorizer()
X_train = vectorizer.fit_transform(train_texts)
model = MultinomialNB()
model.fit(X_train, train_labels)

test_text = ["This is awesome"]
X_test = vectorizer.transform(test_text)
print("Custom Model Prediction:", model.predict(X_test))

Example 6: Handling Sarcasm and Negations


sarcastic_text = "Oh great, another Monday!"
print("TextBlob Polarity:", TextBlob(sarcastic_text).sentiment.polarity)
print("VADER Score:", analyzer.polarity_scores(sarcastic_text))

Example 7: Visualizing Sentiment Over Time in Tweets


import matplotlib.pyplot as plt

tweets = [
    "I love my new phone!",
    "This update ruined everything.",
    "Great support as always.",
    "Why is this so buggy now?"
]

polarities = [TextBlob(t).sentiment.polarity for t in tweets]
plt.plot(polarities, marker='o')
plt.title("Sentiment over time")
plt.xlabel("Tweet index")
plt.ylabel("Polarity")
plt.grid(True)
plt.show()

Example 8: Multilingual Sentiment Analysis


from deep_translator import GoogleTranslator

spanish_text = "Este producto es excelente"
translated = GoogleTranslator(source='auto', target='en').translate(spanish_text)
print("Translated Text:", translated)
print("Polarity:", TextBlob(translated).sentiment.polarity)

Example 9: Combining Sentiment Analysis with Topic Modeling


reviews = [
    "Camera is good but battery sucks",
    "Screen is bright and vibrant",
    "Terrible performance in gaming"
]

topics = ["camera", "battery", "screen", "performance"]
for review in reviews:
    for topic in topics:
        if topic in review.lower():
            sentiment = TextBlob(review).sentiment.polarity
            print(f"Topic: {topic}, Sentiment: {sentiment}")

Example 10: Sentiment Analysis for Product Reviews


reviews = [
    "The service was great!",
    "I will never buy from here again.",
    "Fast delivery and awesome quality."
]

for r in reviews:
    print(f"Review: {r}")
    print("Polarity:", TextBlob(r).sentiment.polarity)
    print("VADER:", analyzer.polarity_scores(r))
    print("---")