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.
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)
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
scores = analyzer.polarity_scores(text)
print("VADER Scores:", scores)
from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
result = sentiment_pipeline(text)
print("Transformers Result:", result)
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'}")
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))
sarcastic_text = "Oh great, another Monday!"
print("TextBlob Polarity:", TextBlob(sarcastic_text).sentiment.polarity)
print("VADER Score:", analyzer.polarity_scores(sarcastic_text))
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()
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)
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}")
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("---")