# Sentiment Analysis for Social Media Posts using VADER
# VADER (Valence Aware Dictionary and sEntiment Reasoner) is optimized for social media text,
# handling slang, emojis, punctuation, and capitalization effectively.
#
# Installation:
# pip install vaderSentiment
#
# This script:
# 1. Analyzes a list of social media posts.
# 2. Computes sentiment scores (compound score: -1 to +1).
# 3. Classifies as 'positive', 'negative', or 'neutral'.
# 4. Includes optional basic preprocessing (remove URLs, mentions, hashtags).
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import re
def preprocess_text(text):
"""
Basic preprocessing for social media text:
- Remove URLs
- Remove @mentions and #hashtags
- Normalize whitespace
"""
text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE) # Remove URLs
text = re.sub(r'@\w+|#\w+', '', text) # Remove mentions and hashtags
text = re.sub(r'\s+', ' ', text).strip() # Normalize whitespace
return text
def analyze_sentiment(posts, preprocess=True):
"""
Analyze sentiment of a list of social media posts.
Args:
posts (list[str]): List of social media post texts.
preprocess (bool): Whether to apply basic preprocessing.
Returns:
list[dict]: List of results with text, scores, and sentiment label.
"""
analyzer = SentimentIntensityAnalyzer()
results = []
for text in posts:
processed_text = preprocess_text(text) if preprocess else text
scores = analyzer.polarity_scores(processed_text)
# Classify based on compound score (standard VADER thresholds)
compound = scores['compound']
if compound >= 0.05:
sentiment = 'positive'
elif compound <= -0.05:
sentiment = 'negative'
else:
sentiment = 'neutral'
results.append({
'original_text': text,
'processed_text': processed_text,
'neg': round(scores['neg'], 3), # Negative score
'neu': round(scores['neu'], 3), # Neutral score
'pos': round(scores['pos'], 3), # Positive score
'compound': round(compound, 3), # Overall sentiment (-1 to +1)
'sentiment': sentiment
})
return results
# Example usage with sample social media posts
if __name__ == "__main__":
sample_posts = [
"I absolutely LOVE this new iPhone! Best upgrade ever! 🔥😍 #Apple",
"Worst service ever. My order never arrived. @CompanyX is a scam! 😡",
"Just watched the new Marvel movie. It was okay, nothing groundbreaking.",
"Can't wait for the weekend! 🌴🍹",
"This app crashes all the time. Fix it please! https://bugreport.com"
]
results = analyze_sentiment(sample_posts)
print("Sentiment Analysis Results:")
print("-" * 80)
for result in results:
print(f"Text: {result['original_text']}")
print(f"Processed: {result['processed_text']}")
print(f"Scores (neg/neu/pos/compound): {result['neg']}/{result['neu']}/{result['pos']}/{result['compound']}")
print(f"Sentiment: {result['sentiment'].upper()}")
print("-" * 80)
Output Example:
code
Sentiment Analysis Results:
--------------------------------------------------------------------------------
Text: I absolutely LOVE this new iPhone! Best upgrade ever! 🔥😍 #Apple
Processed: I absolutely LOVE this new iPhone! Best upgrade ever!
Scores (neg/neu/pos/compound): 0.0/0.149/0.851/0.923
Sentiment: POSITIVE
--------------------------------------------------------------------------------
Text: Worst service ever. My order never arrived. @CompanyX is a scam! 😡
Processed: Worst service ever. My order never arrived. is a scam!
Scores (neg/neu/pos/compound): 0.352/0.648/0.0/-0.6239
Sentiment: NEGATIVE
--------------------------------------------------------------------------------
... (and so on)
Key Features:
VADER: Handles emojis (😍 → positive), ALL CAPS (strong emphasis), slang, and punctuation (!!! → intensity).
Preprocessing: Optional removal of noise common in social media (URLs, @mentions, #hashtags).