Comprehending the Objective
I'm starting to grasp the core requirement: a Python program to scrape and analyze social media hashtags. This forms the foundation for my thought process, guiding my exploration into how such a program might function.
Weighing the Options
I've been assessing the challenges and contemplating the best demonstration approach. Accessing APIs proves restrictive, especially with financial barriers and developer credentials needed for full-fledged solutions. Web scraping's fragility and legal uncertainties are another hurdle. Now, I'm examining third-party library options, hoping they simplify data retrieval while respecting platform ToS.
Prioritizing Twitter (X)
I've refined my focus to Twitter (X) for hashtag analysis. The initial plan involves using Tweepy, the official API wrapper, for stability and compliance. Recognizing API access hurdles, I'll also include a mock data version for immediate analysis. This ensures users can test the core analysis functions without delay.
Building the Mock Data
I'm now fully immersed in developing the code structure. I've begun establishing the essential libraries (tweepy, pandas, textblob, wordcloud, and matplotlib). I'm also creating a mock data generator class that simulates the Twitter API response, which will be accessible even without a paid Twitter API key. This will ensure users can interact and test the analysis logic of the solution easily.
Analyzing the Code Structure
I'm solidifying the final structure of the Python program. I've designed four modular components: configuration, data gathering (with a mock data option), processing (including text cleaning and sentiment analysis), and visualization. Explanations for each step are being added to provide context and ensure ethical considerations regarding web scraping are explicitly addressed. I've also revised the scope, deciding to focus on Twitter data retrieval initially. Finally, the program's libraries are reviewed for consistency, including pandas, textblob, and matplotlib alongside the mock data generator, ensuring the project is easily tested.
Defining Core Functions
I'm now focusing on defining the crucial functions within the HashtagAnalyzer class. I've outlined the methods: fetch_tweets (data retrieval), analyze_sentiment (sentiment calculation), generate_wordcloud (word cloud visualization), and plot_stats (statistical plotting). The final stage will be the main execution block that ties everything together. The program's libraries are reviewed for consistency, including pandas, textblob, and matplotlib alongside the mock data generator.
This is a complex task because major social media platforms (Twitter/X, Instagram, TikTok) have strict anti-scraping measures and expensive APIs.
Below is a complete, modular Python solution. I have designed it to work in two modes:
- API Mode: Uses the official Twitter (X) API (requires a developer account).
- Mock Mode: Generates realistic dummy data so you can run and test the analysis logic immediately without needing API keys.
Prerequisites
You will need to install the following libraries:
pip install tweepy pandas textblob wordcloud matplotlib
tweepy: For accessing the Twitter API.
pandas: For data manipulation.
textblob: For Natural Language Processing (Sentiment Analysis).
wordcloud: To visualize the most common words.
The Python Program
Save this code as hashtag_analyzer.py.
import tweepy
import pandas as pd
import matplotlib.pyplot as plt
from textblob import TextBlob
from wordcloud import WordCloud
import re
import random
from datetime import datetime, timedelta
class HashtagAnalyzer:
def __init__(self, bearer_token=None):
"""
Initialize the analyzer.
If bearer_token is provided, it uses real Twitter API.
Otherwise, it uses a Mock generator for testing.
"""
self.api_mode = False
if bearer_token:
self.client = tweepy.Client(bearer_token=bearer_token)
self.api_mode = True
print("--- RUNNING IN REAL API MODE ---")
else:
print("--- RUNNING IN MOCK DATA MODE (No API Key Provided) ---")
def clean_text(self, text):
"""Removes URLs, mentions, and special characters."""
text = re.sub(r'http\S+', '', text) # Remove URLs
text = re.sub(r'@\w+', '', text) # Remove mentions
text = re.sub(r'#', '', text) # Remove hashtag symbol (keep word)
text = re.sub(r'[^\w\s]', '', text) # Remove punctuation
return text.strip()
def get_sentiment(self, text):
"""Returns Polarity: -1 (Negative) to 1 (Positive)."""
analysis = TextBlob(text)
return analysis.sentiment.polarity
def categorize_sentiment(self, score):
if score > 0.1: return 'Positive'
elif score < -0.1: return 'Negative'
else: return 'Neutral'
def generate_mock_data(self, hashtag, count=50):
"""Generates fake social media data for demonstration."""
topic_words = ["amazing", "terrible", "okay", "love it", "hate it", "best ever", "worst", "scam", "innovation", "buy now"]
data = []
for _ in range(count):
base_text = f"I think {hashtag} is {random.choice(topic_words)} because {random.randint(1,100)}"
data.append({
'created_at': datetime.now() - timedelta(minutes=random.randint(1, 1000)),
'text': base_text,
'likes': random.randint(0, 500),
'retweets': random.randint(0, 100),
'user': f"User_{random.randint(1000,9999)}"
})
return pd.DataFrame(data)
def fetch_tweets(self, hashtag, count=50):
"""Fetches tweets using Tweepy (API) or Mock Data."""
print(f"Fetching data for: {hashtag}...")
if not self.api_mode:
df = self.generate_mock_data(hashtag, count)
else:
try:
# API V2 Query
query = f'{hashtag} -is:retweet lang:en'
tweets = self.client.search_recent_tweets(
query=query,
max_results=min(count, 100), # API max is 100 per request usually
tweet_fields=['created_at', 'public_metrics', 'author_id']
)
if not tweets.data:
print("No tweets found.")
return pd.DataFrame()
data = []
for tweet in tweets.data:
data.append({
'created_at': tweet.created_at,
'text': tweet.text,
'likes': tweet.public_metrics['like_count'],
'retweets': tweet.public_metrics['retweet_count'],
'user': tweet.author_id
})
df = pd.DataFrame(data)
except Exception as e:
print(f"Error fetching from API: {e}")
return pd.DataFrame()
# Process Data
df['clean_text'] = df['text'].apply(self.clean_text)
df['sentiment_score'] = df['clean_text'].apply(self.get_sentiment)
df['sentiment_category'] = df['sentiment_score'].apply(self.categorize_sentiment)
return df
def generate_report(self, df, hashtag):
if df.empty:
print("No data to analyze.")
return
print(f"\n--- ANALYSIS REPORT FOR {hashtag} ---")
print(f"Total Tweets Analyzed: {len(df)}")
print(f"Average Likes: {df['likes'].mean():.2f}")
print(f"Average Sentiment: {df['sentiment_score'].mean():.2f}")
print("\nTop 3 Most Liked Tweets:")
print(df.nlargest(3, 'likes')[['text', 'likes']])
# --- Visualizations ---
plt.figure(figsize=(15, 5))
# 1. Sentiment Distribution Bar Chart
plt.subplot(1, 2, 1)
df['sentiment_category'].value_counts().plot(kind='bar', color=['green', 'grey', 'red'])
plt.title(f'Sentiment Distribution for {hashtag}')
plt.xlabel('Sentiment')
plt.ylabel('Count')
# 2. Word Cloud
all_words = ' '.join([text for text in df['clean_text']])
wordcloud = WordCloud(width=800, height=500, random_state=21, max_font_size=110).generate(all_words)
plt.subplot(1, 2, 2)
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis('off')
plt.title(f'Word Cloud for {hashtag}')
plt.tight_layout()
plt.show()
# --- MAIN EXECUTION ---
if __name__ == "__main__":
# OPTION 1: Use Real API (Fill this if you have a Twitter Developer Account)
# bearer_token = "YOUR_TWITTER_API_BEARER_TOKEN_HERE"
# OPTION 2: Leave None to use Mock Mode (Works immediately)
bearer_token = None
# Create Analyzer
app = HashtagAnalyzer(bearer_token)
# inputs
target_hashtag = "#Python"
num_tweets = 50
# Run
df = app.fetch_tweets(target_hashtag, num_tweets)
app.generate_report(df, target_hashtag)
How this code works
1. HashtagAnalyzer Class
This class handles the connection. If you provide a bearer_token (from Twitter Developer Portal), it connects to the real internet. If not, it activates generate_mock_data.
2. Data Cleaning (clean_text)
Social media data is messy containing Emojis, URLs, and mentions (@username). This function uses Regular Expressions (re) to strip the noise so the sentiment analyzer reads "I love this" rather than "I love this http://bit.ly/..."
3. Sentiment Analysis (TextBlob)
We use TextBlob to assign a score to every tweet:
- Polarity: A float between -1 (very negative) and +1 (very positive).
- We categorize these into Positive, Neutral, or Negative buckets.
4. Visualization (Matplotlib & WordCloud)
- Bar Chart: Shows the ratio of positive vs. negative tweets.
- Word Cloud: Isolate the most frequently used words alongside the hashtag. This helps identify context. (e.g., If analyzing
#Apple, are the related words "Pie/Cinnamon" or "iPhone/Tech"?).
How to get real data (Twitter/X API)
To make this work with real data:
- Go to the Twitter Developer Portal.
- Sign up for a "Free" (limited) or "Basic" (paid) account.
- Create a Project and an App.
- Copy the Bearer Token.
- Paste it into the
bearer_token variable at the bottom of the script.
Limitations & Ethical Warnings
- Scraping vs. API: Scraping sites like Instagram or TikTok without an API using tools like Selenium is possible but often violates Terms of Service (ToS) and leads to IP bans. This script uses the API method (for Twitter) which is the compliant way to do it.
- Rate Limits: The free Twitter API is very limited (you can only fetch a small number of tweets per month).
- TikTok/Instagram: These platforms are "walled gardens." They do not provide text-search APIs easily. Analyzing them usually requires enterprise-level scraping tools or official partner APIs.