Analyze Twitter data in Python: a worked example
Analyze Twitter data in Python with a runnable script: fetch tweets, analyse tweets in Python with the standard library, and chart the results with matplotlib.
Piyushh · November 13, 2026 · 2 min read

To analyze Twitter data in Python, you need three steps: fetch tweets as JSON, shape them into rows, and summarise the rows. The script in this post does all three and runs as written. It uses requests and the standard library, so the only thing to install is pip install requests.
The worked example analyses a recorded search for the phrase "crm recommendation". It counts the likes on the posts, looks at when they were written, finds the post that did best and checks where the authors say they live. You can swap in your own query.
The data: one search call
x.search returns tweets with their engagement counts and the author's profile attached. One page holds about 20 tweets and costs 2 credits.
curl "https://api.chatterapi.com/v1/x/tweets/search?q=%22crm%20recommendation%22&sort=latest" \
-H "Authorization: Bearer $CHATTERAPI_KEY"
Each row has text, createdAt, likes, retweets, replies, views, lang and an author object with handle, followers and location. Pagination works through a page.nextCursor that you pass back as cursor. A test key (ca_test_...) returns one recorded page for free no matter what you ask, so it's a good key to build the script with.
The script
That's the full analysis. Give it a saved JSON file and it runs on recorded data; run it with no argument and it calls the API with your key.
import os, statistics, collections, datetime as dt
def tweets_from(rows):
"""Keep only the fields we analyse."""
for t in rows:
a = t["author"]
yield {
"when": dt.datetime.fromisoformat(t["createdAt"].replace("Z", "+00:00")),
"likes": t["likes"], "retweets": t["retweets"], "replies": t["replies"],
"views": t["views"] or 0, "handle": a["handle"], "followers": a["followers"],
"location": a["location"], "lang": t["lang"], "text": t["text"],
}
def report(tweets):
n = len(tweets)
print(f"{n} tweets, {min(t['when'] for t in tweets):%Y-%m-%d} to {max(t['when'] for t in tweets):%Y-%m-%d}")
likes = [t["likes"] for t in tweets]
print(f"likes: mean {statistics.mean(likes):.1f}, median {statistics.median(likes)}, max {max(likes)}")
by_year = collections.Counter(t["when"].strftime("%Y") for t in tweets)
print("by year:", dict(sorted(by_year.items())))
for t in sorted(tweets, key=lambda t: t["likes"], reverse=True)[:3]:
print(f" {t['likes']:>4} likes @{t['handle']} {t['text'][:50]!r}")
located = [t["location"] for t in tweets if t["location"]]
print(f"{len(located)} of {n} authors list a location; most common:", collections.Counter(located).most_common(3))
print("authors:", len({t['handle'] for t in tweets}), "distinct; languages:", dict(collections.Counter(t['lang'] for t in tweets)))
if __name__ == "__main__":
import json, sys
if len(sys.argv) > 1: # recorded sample
rows = json.load(open(sys.argv[1]))["data"]
else: # live key
import requests
r = requests.get("https://api.chatterapi.com/v1/x/tweets/search",
params={"q": '"crm recommendation"', "sort": "latest"},
headers={"Authorization": f"Bearer {os.environ['CHATTERAPI_KEY']}"}, timeout=60)
r.raise_for_status()
rows = r.json()["data"]
report(list(tweets_from(rows)))
What it printed
We ran the script on the recorded x.search sample, a test-key response captured 2026-10-13. Here is the real output:
20 tweets, 2019-11-24 to 2026-09-14
likes: mean 4.7, median 2.5, max 34
by year: {'2019': 2, '2020': 5, '2021': 2, '2022': 3, '2023': 2, '2024': 2, '2025': 1, '2026': 3}
34 likes @mds 'Anyone have a CRM recommendation? Something super '
9 likes @mouthofmorrison '@retornam @mattocko @bryce He’s not going to give '
6 likes @steiny "In the near future I've got to mail a bunch of peo"
19 of 20 authors list a location; most common: [('Marietta, GA', 1), ('Bengaluru', 1), ('India', 1)]
authors: 20 distinct; languages: {'en': 20}
How to read it:
- A mean of 4.7 against a median of 2.5 means a few posts pull the average up. Quote the median.
- The by-year counts spread from 2019 to 2026 because this is a "latest" search on a narrow phrase, not a dense feed. Twenty rows is a sample, so don't read a trend into it.
- The top post is a plain question asking for a tool, which is the pattern lead hunters look for.
- Locations are free text the authors typed in. This guide explains why you shouldn't treat them as exact.
Analyse tweets in Python at scale
A single page works as a demo. For a real dataset, loop over pages with a hard cap and save the rows:
def pages(q, max_pages=5):
cursor = None
for _ in range(max_pages):
params = {"q": q, "sort": "latest", **({"cursor": cursor} if cursor else {})}
r = requests.get("https://api.chatterapi.com/v1/x/tweets/search", params=params,
headers={"Authorization": f"Bearer {os.environ['CHATTERAPI_KEY']}"}, timeout=60)
r.raise_for_status()
body = r.json()
yield from body["data"]
cursor = body["page"]["nextCursor"]
if not body["page"]["hasMore"] or not cursor:
break
max_pages=5 caps the spend at 10 credits. Pass the result to tweets_from and report as before. To save and de-duplicate a large pull, read how to build a Twitter dataset. For a time window, search tweets by date covers the since and until parameters.
Twitter data visualization in Python
The same rows can feed a chart. Install matplotlib and plot likes per tweet over time:
import matplotlib.pyplot as plt
rows = list(tweets_from(rows))
plt.scatter([t["when"] for t in rows], [t["likes"] for t in rows])
plt.ylabel("likes")
plt.title("Tweets mentioning 'crm recommendation'")
plt.savefig("likes_over_time.png", dpi=150)
We didn't run this snippet for the post, so try it on your own data first. Past a few hundred rows, load the dataset into pandas for grouping and rolling averages. The Twitter API Python guide shows how to pull timelines and follower lists into the same structure.
Run it yourself
Get a key, set CHATTERAPI_KEY and run the script. A test key is enough to watch it work end to end.
Sign up to run the script with a test key at no cost.