Clarifying scraping needs
The user is asking for a Python program to scrape and analyze social media hashtags but didn't specify which platform—like Twitter/X, Instagram, or TikTok. I need to think about the legal and ethical implications of scraping social media, ensuring we don't violate Terms of Service or bypass restrictions. I should clarify the target platform and desired metrics, like frequency or sentiment. It might also help to provide a general framework for using official APIs, focusing on Twitter/X as a canonical example.Planning the program structure
I need to decide between using SQLite or CSV for data storage and then analyze aspects like counts, top users, co-occurring hashtags, time-of-day trends, and sentiment analysis using NLTK/VADER or TextBlob. The user didn’t specify how detailed they want the information, so I’ll aim for concise yet comprehensive code. It’s best to start by asking a clarifying question. Since they want a Python program, I'll assume they’d appreciate sample code, ideally leveraging the X API for its straightforward hashtag handling. I'll ensure the design is modular for flexibility with different APIs.Choosing the right tools
I want to ensure the code I provide isn’t outdated. I plan to use the Tweepy Client (v4) with the X API v2 and the search_recent_tweets method. Alternatively, there's the option to use the snscrape library, which can scrape public content without the official API, but that could violate Terms of Service. It's crucial to avoid suggesting methods to bypass official APIs, so I’ll stick with using Tweepy and API keys for a proper implementation.Designing the program
I'm outlining the structure for the program. It includes a config.py file for API keys or environment variables and a main script that retrieves hashtags. For each hashtag, I'll fetch tweets from the past week using search_recent_tweets, collecting fields like ID, text, creation date, author ID, language, and public metrics, then store everything in a Pandas DataFrame.
For analysis, I plan to count tweets per hashtag, group them by time for frequency, extract other hashtags using regex, and compute co-occurring hashtags. I'll perform sentiment analysis with NLTK's VADER, noting that while it requires an extra download, TextBlob is simpler. Finally, I'll print summary stats and optionally save the results to CSV or generate graphs, while ensuring we respect Terms of Service and avoid excessive request volumes.Creating the Hashtag Analysis Program
I want to ensure that my code focuses on analyzing hashtag trends without suggesting any misuse. I’ll begin by outlining necessary requirements, such as using Tweepy, Pandas, NLTK, and Matplotlib.
The program will include a setup for API keys and a main script that retrieves and analyzes tweets based on provided hashtags. I’ll also need to mention the importance of following Terms of Service and avoiding any private or internal endpoints, especially for platforms like Instagram.
The structure will include functions for fetching tweets, analyzing frequency, performing sentiment analysis, and extracting co-occurring hashtags, all while keeping dependencies minimal. This means relying on standard libraries alongside Tweepy and NLTK, ensuring we avoid complexity while meeting the user's needs effectively. Below is a complete example of a Python program that:
- Uses the official X (Twitter) API to collect tweets containing a hashtag
- Performs basic analysis: volume, co-occurring hashtags, engagement metrics, and sentiment
You can adapt the analysis part to any platform; only the “data collection” part changes across social networks. Always respect each platform’s Terms of Service and local law, and use official APIs where required.
1. Setup
1.1. Get API access
- Create a developer account for X (Twitter) at:
https://developer.x.com/
- Create a project/app and obtain at least a Bearer Token.
- Save it as an environment variable, e.g.:
export TWITTER_BEARER_TOKEN="YOUR_BEARER_TOKEN_HERE"
(Use a .env or your OS’s secret manager in real deployments.)
1.2. Install dependencies
pip install tweepy pandas nltk matplotlib
2. The Python program: hashtag_analyzer.py
#!/usr/bin/env python3
"""
hashtag_analyzer.py
Scrapes recent tweets containing a given hashtag via the official X (Twitter) API
and performs simple analytics:
- Tweet volume
- Basic engagement stats
- Co-occurring hashtags
- Sentiment analysis (using NLTK VADER)
Usage:
python hashtag_analyzer.py
You will be prompted for:
- Hashtag (without #, e.g. "python")
- Max number of tweets to fetch
Prerequisites:
- Environment variable TWITTER_BEARER_TOKEN set.
- pip install tweepy pandas nltk matplotlib
"""
import os
import re
from collections import Counter
from datetime import timezone
import tweepy
import pandas as pd
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer
import matplotlib.pyplot as plt
# -------------------- Helpers: Sentiment -------------------- #
def ensure_vader_downloaded():
"""Download VADER lexicon if not already present."""
try:
nltk.data.find("sentiment/vader_lexicon")
except LookupError:
nltk.download("vader_lexicon")
# -------------------- Scraping via X (Twitter) API -------------------- #
def create_twitter_client() -> tweepy.Client:
"""Create a Tweepy client using the Bearer Token from environment."""
bearer_token = os.getenv("TWITTER_BEARER_TOKEN")
if not bearer_token:
raise RuntimeError(
"TWITTER_BEARER_TOKEN is not set. "
"Export it in your shell or environment manager."
)
client = tweepy.Client(
bearer_token=bearer_token,
wait_on_rate_limit=True, # Automatically sleeps when rate-limited
)
return client
def fetch_hashtag_tweets(client: tweepy.Client,
hashtag: str,
max_tweets: int = 200) -> pd.DataFrame:
"""
Fetch recent tweets containing the given hashtag using X API v2.
Parameters
----------
client : tweepy.Client
Authenticated Tweepy client.
hashtag : str
Hashtag without the leading '#', e.g., "python".
max_tweets : int
Maximum number of tweets to fetch (API returns up to 100 per page).
Returns
-------
pandas.DataFrame
Columns: id, text, created_at, like_count, retweet_count, reply_count,
quote_count, lang
"""
query = f"#{hashtag} -is:retweet -is:reply lang:en"
tweet_fields = [
"created_at",
"lang",
"public_metrics" # includes likes, retweets, replies, quotes
]
records = []
print(f"Fetching up to {max_tweets} tweets for #{hashtag} ...")
paginator = tweepy.Paginator(
client.search_recent_tweets,
query=query,
tweet_fields=tweet_fields,
max_results=100, # max allowed per request
)
count = 0
for tweet in paginator.flatten(limit=max_tweets):
metrics = tweet.data.get("public_metrics", {})
records.append({
"id": tweet.id,
"text": tweet.text,
"created_at": tweet.created_at.astimezone(timezone.utc),
"like_count": metrics.get("like_count", 0),
"retweet_count": metrics.get("retweet_count", 0),
"reply_count": metrics.get("reply_count", 0),
"quote_count": metrics.get("quote_count", 0),
"lang": tweet.lang,
})
count += 1
if not records:
print("No tweets returned for this hashtag.")
return pd.DataFrame()
df = pd.DataFrame(records)
print(f"Fetched {len(df)} tweets.")
return df
# -------------------- Hashtag & Text Utilities -------------------- #
HASHTAG_REGEX = re.compile(r"#(\w+)", flags=re.UNICODE)
def extract_hashtags(text: str):
"""Return a list of hashtags (without #, lowercased) from a tweet text."""
return [m.lower() for m in HASHTAG_REGEX.findall(text)]
def find_cooccurring_hashtags(df: pd.DataFrame, main_hashtag: str, top_n: int = 10):
"""
Find the top-N co-occurring hashtags that appear with `main_hashtag`.
"""
main_hashtag = main_hashtag.lower()
counter = Counter()
for text in df["text"]:
tags = set(extract_hashtags(text))
if main_hashtag in tags:
tags.remove(main_hashtag)
counter.update(tags)
return counter.most_common(top_n)
# -------------------- Sentiment Analysis -------------------- #
def add_sentiment_scores(df: pd.DataFrame) -> pd.DataFrame:
"""
Add sentiment scores (compound, pos, neu, neg) using NLTK VADER.
"""
ensure_vader_downloaded()
sia = SentimentIntensityAnalyzer()
scores = df["text"].apply(sia.polarity_scores)
scores_df = pd.DataFrame(list(scores))
df = pd.concat([df.reset_index(drop=True), scores_df], axis=1)
return df
def classify_sentiment(compound_score: float) -> str:
"""
Classify sentiment from compound score:
- >= 0.05 -> positive
- <= -0.05 -> negative
- otherwise -> neutral
"""
if compound_score >= 0.05:
return "positive"
elif compound_score <= -0.05:
return "negative"
else:
return "neutral"
# -------------------- Analysis & Reporting -------------------- #
def summarize_basic_stats(df: pd.DataFrame, hashtag: str):
print("\n=== BASIC STATISTICS ===")
print(f"Hashtag: #{hashtag}")
print(f"Number of tweets: {len(df)}")
print(f"Time range: {df['created_at'].min()} -> {df['created_at'].max()}")
print("\nAverage engagement per tweet:")
print(f" Likes: {df['like_count'].mean():.2f}")
print(f" Retweets:{df['retweet_count'].mean():.2f}")
print(f" Replies: {df['reply_count'].mean():.2f}")
print(f" Quotes: {df['quote_count'].mean():.2f}")
def summarize_cooccurring_hashtags(df: pd.DataFrame, main_hashtag: str):
print("\n=== TOP CO-OCCURRING HASHTAGS ===")
top_co = find_cooccurring_hashtags(df, main_hashtag, top_n=15)
if not top_co:
print("No co-occurring hashtags found.")
return
for tag, count in top_co:
print(f" #{tag}: {count}")
def summarize_sentiment(df: pd.DataFrame):
print("\n=== SENTIMENT ANALYSIS ===")
df = df.copy()
df["sentiment_label"] = df["compound"].apply(classify_sentiment)
sentiment_counts = df["sentiment_label"].value_counts(normalize=True) * 100
for label in ["positive", "neutral", "negative"]:
pct = sentiment_counts.get(label, 0.0)
print(f" {label.capitalize():8}: {pct:5.1f}% of tweets")
print(f"\nAverage compound sentiment: {df['compound'].mean():.3f}")
return df
def plot_activity_over_time(df: pd.DataFrame, hashtag: str):
"""
Plot tweet volume over time (grouped by hour).
"""
print("\nGenerating simple time-series plot (tweets per hour)...")
df = df.copy()
df["hour"] = df["created_at"].dt.floor("H")
counts = df.groupby("hour")["id"].count()
plt.figure(figsize=(10, 4))
counts.plot(kind="line", marker="o")
plt.title(f"Volume of #{hashtag} tweets over time")
plt.xlabel("Time (UTC, per hour)")
plt.ylabel("Number of tweets")
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# -------------------- Main Program -------------------- #
def main():
hashtag = input("Enter a hashtag (without #, e.g. python): ").strip().lstrip("#")
if not hashtag:
print("No hashtag provided. Exiting.")
return
try:
max_tweets = int(input("Max number of tweets to fetch (e.g. 300): ").strip())
except ValueError:
max_tweets = 300
print("Invalid number; defaulting to 300.")
client = create_twitter_client()
df = fetch_hashtag_tweets(client, hashtag, max_tweets=max_tweets)
if df.empty:
return
# Save raw data
out_csv = f"tweets_{hashtag}.csv"
df.to_csv(out_csv, index=False)
print(f"\nSaved raw tweet data to {out_csv}")
# Basic stats
summarize_basic_stats(df, hashtag)
# Co-occurring hashtags
summarize_cooccurring_hashtags(df, hashtag)
# Sentiment
df = add_sentiment_scores(df)
df_with_sentiment = summarize_sentiment(df)
# (Optional) Save with sentiment
out_csv_sent = f"tweets_{hashtag}_with_sentiment.csv"
df_with_sentiment.to_csv(out_csv_sent, index=False)
print(f"Saved tweet data with sentiment to {out_csv_sent}")
# Plot activity over time
plot_activity_over_time(df, hashtag)
if __name__ == "__main__":
main()
3. How to run
python hashtag_analyzer.py
Then:
- Enter the hashtag (e.g.
python)
- Enter maximum tweets (e.g.
500)
The script will:
- Fetch recent tweets (subject to API limits)
- Print:
- Number of tweets and time range
- Average engagement metrics
- Top co-occurring hashtags
- Sentiment distribution
- Save:
tweets_<hashtag>.csv (raw data)
tweets_<hashtag>_with_sentiment.csv (includes sentiment scores)
- Display a simple time-series plot of tweet volume over time.
If you tell me which platform(s) you specifically care about (e.g., TikTok, Reddit, Mastodon, LinkedIn), I can adapt the data-collection layer to that API and keep the same analysis pipeline.