Mining Twitter and Facebook
Practical study notes on how engineers collect, clean, and analyse Twitter and Facebook data for social-network and behaviour analysis, with definitions, APIs, sampling issues, example Python parsers, formulas, and exam guidance.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Mining Twitter and Facebook gives engineers structured access to real-world social interactions and user-generated text. Engineers use these data for tasks such as influence analysis, trend detection, user behaviour modelling, and building recommendations or alert systems in production.
Key ideas
Start from first principles: social-media platforms store objects (users, posts, reactions) and relations (authoring, replying, mentioning, following). Mining means extracting those objects and relations under constraints of APIs, privacy and sampling.
Social object: any primary unit produced by users. Example: a tweet (Twitter post) or a Facebook post. Define object fields: id, author_id, text/body, created_at, language, attachments.
Edge / Relation: a directed or undirected link between social objects or actors. Examples: author-of (user -> post), mention (post -> user), reply-to (post -> post), share/retweet (user -> post), follow (user -> user), like/react (user -> post). Always state direction.
Graph view: represent the dataset as a graph G = (V, E) where V is the set of actors and/or posts and E is relations. Two common projections:
- User-user graph: nodes are users, edges are follow or mention or reply relations.
- Bipartite user-post graph: nodes split into users and posts; author-of edges link them.
To draw: sketch two columns, left for users (u1,u2,u3), right for posts (p1,p2,p3). Draw arrows from u1 to p1 labeled "author-of", arrow from p1 to u2 labeled "mentions", arrow between u2->u3 labeled "follows".
APIs and access modes: two main modes: REST (pull) and Streaming (push). REST returns snapshots (pages) on request; streaming pushes new events in real time. Both use authenticated requests (OAuth). On Twitter/X v2, push access is via sampled and filtered stream endpoints; on Facebook, push is typically delivered via Webhooks subscriptions rather than a long‑lived streaming socket.
Pagination and rate limits: APIs return limited pages. Define rate limit: the maximum number of API calls allowed in a time window. Engineers must implement backoff and resume based on pagination tokens. Handle HTTP 429 Too Many Requests and honor Retry-After headers when backing off.
Identifiers and types: treat platform IDs as opaque strings, not integers (to avoid overflow or leading-zero issues). Retweet vs quote: a retweet creates a new post with its own id that references the original post id (e.g., referenced_tweets type='retweeted'); a quote embeds the user's text plus a link/reference to the original.
Sampling biases: any API-based sample is not a random sample of the population. State: "If sampling depends on activity (e.g., streaming keyword filter), the observed degree distribution is biased toward active users." Derive reason: probability a user appears ∝ their activity rate.
Privacy and terms: consent and platform terms of service govern what data you may collect, store, and publish. Always check platform policies before release. For Twitter/X research outputs, redistribute only Tweet IDs and User IDs (rehydration by downstream users) rather than full content, unless explicitly permitted by the current policy.
Data cleaning steps: deduplicate posts by id, normalize timezones to UTC, handle deleted accounts and removed content, detect and remove bot-like accounts (heuristics: extremely high posting rate, identical content), expand shortened URLs only if allowed.
Basic features for mining: textual features (tokens, hashtags, mentions), temporal features (timestamp, inter-arrival), network features (in-degree/out-degree, reciprocity), engagement (likes, shares, comments). For text, common practice: lowercase, remove stopwords, tokenize, possibly lemmatize.
Engagement and influence metrics: define engagement rate = (likes + comments + shares)/followers. State assumptions: followers > 0; use 30-day follower count snapshot.
Ethical constraints: anonymize when required, avoid deanonymization, and follow institution ethics policies.
Formulas
engagement_rate = (likes + comments + shares) / followers
- likes, comments, shares: counts (unitless); followers: count (unitless). Applies to computing a simple per-post engagement fraction.
avg_post_rate = total_posts / observation_time
- total_posts: count; observation_time: seconds (s). Gives average posts per second by a user in the window.
degree_centrality(u) = deg(u) / (n - 1)
- deg(u): degree of node u (count); n: number of nodes. Unitless. For undirected projections.
tf(t,d) = count of term t in document d
- raw term-frequency. Unitless.
tf-idf(t,d,D) = tf(t,d) * log((1 + |D|) / (1 + df(t))) (natural log unless stated otherwise)
- |D|: number of documents; df(t): number of docs containing term t. Unitless.
Syntax notes to remember (APIs and common libraries):
GET https://api.twitter.com/2/tweets?ids=<comma-separated-ids>&tweet.fields=created_at,author_id
GET https://graph.facebook.com/<node_id>?fields=message,created_time,from,shares
Authorization: Bearer <ACCESS_TOKEN>
Cursor-based pagination: next_token / paging.next (store and reuse token for subsequent requests)
(Exact endpoint parameters change with API versions—verify before use.)
Worked examples
Example 1 — Python: parse a downloaded small Twitter JSON (no network calls). The program counts tweets, extracts hashtags, and builds a mention adjacency.
Program parse_twitter.py:
# parse_twitter.py
import json
from collections import Counter, defaultdict
def analyze_tweets(tweets_json):
tweets = json.loads(tweets_json)
n = len(tweets)
hashtag_counts = Counter()
mention_adj = defaultdict(set) # user -> set of mentioned users
for t in tweets:
uid = str(t.get('author_id'))
text = t.get('text','')
for token in text.split():
if token.startswith('#'):
hashtag_counts[token.lower()] += 1
if token.startswith('@'):
mention_adj[uid].add(token[1:])
return n, hashtag_counts, {u:list(v) for u,v in mention_adj.items()}
if __name__ == '__main__':
sample = '''[
{"id":"1","author_id":"100","text":"Hello world #intro @alice"},
{"id":"2","author_id":"101","text":"Replying to @bob #intro"},
{"id":"3","author_id":"100","text":"Another post #news"}
]'''
n, hashtags, mentions = analyze_tweets(sample)
print('tweets:', n)
print('hashtags:', hashtags)
print('mentions:', mentions)
Sample input: (internal to program; no external file)
Exact output when run:
tweets: 3 hashtags: Counter({'#intro': 2, '#news': 1}) mentions: {'100': ['alice'], '101': ['bob']}
Example 2 — Python: parse a small Facebook-like JSON of posts and compute engagement and anonymize user ids.
Program parse_facebook.py:
# parse_facebook.py
import json
from collections import defaultdict
def analyze_fb(posts_json):
posts = json.loads(posts_json)
out = []
for p in posts:
pid = p['id']
uid = 'user_' + str(p['from']['id']).zfill(4)[-4:] # simple anonymize: last 4 digits, zero-padded
likes = p.get('likes',0)
comments = p.get('comments',0)
shares = p.get('shares',0)
followers = p.get('followers',100) or 100
engagement = (likes + comments + shares) / followers
out.append({'post_id':pid, 'anon_user':uid, 'engagement':round(engagement,4)})
return out
if __name__ == '__main__':
sample = '''[
{"id":"p1","from":{"id":555},"likes":10,"comments":2,"shares":1,"followers":200},
{"id":"p2","from":{"id":556},"likes":0,"comments":0,"shares":0,"followers":50}
]'''
print(json.dumps(analyze_fb(sample), indent=2))
Exact output when run:
[ {"post_id": "p1", "anon_user": "user_0555", "engagement": 0.065}, {"post_id": "p2", "anon_user": "user_0556", "engagement": 0.0} ]
Example 3 — Theory model answer (short): "Define sampling bias in streaming collection and how it affects degree distribution."
Model answer: Sampling bias occurs when the mechanism that selects data depends on user behaviour. In streaming keyword filters, active users posting on tracked keywords have higher probability of inclusion; hence observed degree distribution overestimates degrees of active users relative to a uniform sample. Derivation: let activity rate of user i be λ_i; probability user appears in window T is 1 - e^{-λ_i T}, an increasing function of λ_i; so inclusion probability correlates with degree if degree correlates with activity.
Common mistakes
- Confusing retweet with original post when counting unique posts (double counting the same content).
- Ignoring pagination and truncating results when using REST APIs.
- Assuming API samples are random; forgetting to state sampling bias in answers.
- Not normalising times to UTC when computing rates and inter-arrival times.
- Publishing raw user identifiers without checking terms and ethics.
For your exam
Common question types:
- Define and contrast REST vs streaming access. Full marks: clear definitions, example endpoints, mention of pagination and rate limits, short diagram of request-response vs push.
- Short note on sampling bias and its correction. Full marks: state mechanism, math for bias (probability of appearance ∝ activity), practical corrections (weighting by inverse of inclusion probability, if estimable).
- Program/parse question: give a JSON and ask to extract hashtags and mentions. Full marks: correct parsing, deduplication by id, exact output formatting, handle missing fields.
- Diagram question: draw bipartite graph users-posts showing author-of, mention, and follow edges. Full marks: labelled nodes and directed arrows with edge labels.
Always state assumptions, e.g., what fields exist in sample data, whether timestamps are in UTC, and whether follower counts are current snapshots.
Quick check
- What is the main difference between REST and Streaming access?
- Why should you treat social-platform IDs as strings?
- Write the formula for engagement rate used here.
Answers: 1) REST is pull-based paginated snapshots; Streaming is push-based real-time events. 2) Because IDs may be larger than integer types or have leading zeros—treat as opaque strings to avoid numeric errors. 3) engagement_rate = (likes + comments + shares) / followers
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?