Sentiment Analysis is a Natural Language Processing (NLP) technique used to determine whether a given text expresses a positive, negative, or neutral sentiment.
Installing Required Libraries
pip install nltk textblob vaderSentiment
Step 1: Sentiment Analysis with TextBlob
from textblob import TextBlob
text = "I love programming in Python! It's so intuitive and powerful."
# Perform sentiment analysis
analysis = TextBlob(text)
# Sentiment polarity (-1 to 1, where -1 is negative and 1 is positive)
print("Sentiment Polarity:", analysis.sentiment.polarity)
# Sentiment subjectivity (0 to 1, where 0 is objective and 1 is subjective)
print("Sentiment Subjectivity:", analysis.sentiment.subjectivity)
TextBlob is simple and useful for basic sentiment analysis.
Step 2: Sentiment Analysis with VADER (Best for Social Media & Short Texts)
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
text = "This movie was absolutely fantastic! I loved every second of it."
# Compute sentiment scores
scores = analyzer.polarity_scores(text)
print("Sentiment Scores:", scores)
# Determine sentiment
if scores['compound'] >= 0.05:
print("Overall Sentiment: Positive 😊")
elif scores['compound'] <= -0.05:
print("Overall Sentiment: Negative 😠")
else:
print("Overall Sentiment: Neutral 😐")
VADER works best with social media posts and short, informal text.
Step 3: Sentiment Analysis with Machine Learning (Using NLTK & Naive Bayes)
import nltk
from nltk.classify import NaiveBayesClassifier
from nltk.classify.util import accuracy
nltk.download('punkt')
# Training dataset
train_data = [
("I love this phone!", "Positive"),
("This is an amazing experience", "Positive"),
("I hate this movie!", "Negative"),
("This is the worst product ever", "Negative"),
("I am feeling great today!", "Positive"),
("Not a good experience", "Negative"),
]
# Feature extractor
def extract_features(text):
words = nltk.word_tokenize(text.lower())
return {word: True for word in words}
# Prepare dataset
train_set = [(extract_features(text), label) for text, label in train_data]
# Train Naive Bayes classifier
classifier = NaiveBayesClassifier.train(train_set)
# Test a sample sentence
test_text = "I really love this amazing phone!"
print("Prediction:", classifier.classify(extract_features(test_text)))
Naive Bayes is a simple but effective classifier for text-based sentiment analysis.
Applications of Sentiment Analysis
✔ Social Media Monitoring – Analyze Twitter & Facebook posts.
✔ Customer Reviews – Analyze product feedback.
✔ Market Analysis – Understand consumer sentiment for businesses.
✔ Political Analysis – Analyze public opinion on policies & elections.