Skip to content

Twitter Sentiment Analysis

Given tweets and sentiment labels (or sentiment scores):

  • Clean text
  • Explore sentiment distribution
  • Visualize sentiment over time (if timestamps exist)
diagram Twitter sentiment analysis pipeline mermaid
From raw noisy tweets to a clean sentiment distribution.
Load tweets
import pandas as pd
 
df = pd.read_csv("data/tweets.csv")
print(df.head())
Clean text
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)
Sentiment counts
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()
sketch Sentiment distribution p5.js
Bar height shows how many tweets fall into each sentiment bucket.
  • Most common sentiment
  • Examples of strongly positive/negative tweets
  • Trend over time (optional)

Exercise 1 – Strip URLs from text with regex

Section titled “Exercise 1 – Strip URLs from text with regex”

Exercise 3 – Filter tweets mentioning a keyword

Section titled “Exercise 3 – Filter tweets mentioning a keyword”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading