Twitter Sentiment Analysis
Given tweets and sentiment labels (or sentiment scores):
- Clean text
- Explore sentiment distribution
- Visualize sentiment over time (if timestamps exist)
Analysis pipeline
Section titled “Analysis pipeline”flowchart LR A["Raw tweets"] --> B["Clean text
(urls, mentions, hashtags)"] B --> C["Explore
(sentiment counts)"] C --> D["Visualize
(distribution / trend)"] D --> E["Conclude
(dominant sentiment)"]
Step 1: Load
Section titled “Step 1: Load”import pandas as pd
df = pd.read_csv("data/tweets.csv")
print(df.head())Step 2: Basic text cleaning
Section titled “Step 2: Basic text cleaning”import re
def clean_tweet(s: str) -> str:
s = re.sub(r"http\S+", "", s) # remove URLs
s = re.sub(r"@\w+", "", s) # remove mentions
s = re.sub(r"#", "", s) # remove hashtag symbol
s = re.sub(r"\s+", " ", s).strip() # normalize whitespace
return s
if "text" in df.columns:
df["text_clean"] = df["text"].astype(str).apply(clean_tweet)Step 3: Sentiment distribution
Section titled “Step 3: Sentiment distribution”import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(7, 4))
sns.countplot(data=df, x="sentiment")
plt.title("Sentiment distribution")
plt.tight_layout()
plt.show()Visualize it
Section titled “Visualize it”Deliverable
Section titled “Deliverable”- Most common sentiment
- Examples of strongly positive/negative tweets
- Trend over time (optional)
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Strip URLs from text with regex
Section titled “Exercise 1 – Strip URLs from text with regex”Exercise 2 – Sentiment counts
Section titled “Exercise 2 – Sentiment counts”Exercise 3 – Filter tweets mentioning a keyword
Section titled “Exercise 3 – Filter tweets mentioning a keyword”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading