Twitter

How to Make Twitter Sentiment Analysis in Python

By Spencer Lanoue
October 31, 2025

Building your own Twitter sentiment analysis tool with Python gives you a powerful way to understand what people really think about your brand, products, or campaigns. Forget guessing - with a simple script, you can tap into real-time conversations and turn them into actionable insights. This guide will walk you through the entire process, step-by-step, from setting up your environment to visualizing the sentiment of any topic you want to track on X (formerly Twitter).

What is Sentiment Analysis, Really? And Why Should You Care?

In simple terms, sentiment analysis is the process of figuring out the emotional tone behind a piece of text. Is it positive, negative, or neutral? For social media managers and marketers, this isn't just a fun tech project, it's a direct line into your audience's mind. Imagine you've just launched a new marketing campaign. Instead of waiting for sales figures to roll in, you can instantly gauge public reaction by analyzing tweets that mention your campaign hashtag.

Here’s what you can do with it:

  • Track Brand Health: Monitor how people feel about your brand over time. Are conversations generally positive, or is there a growing negative trend you need to address?
  • Get Real-Time Feedback: Get instant, unfiltered feedback on products, services, or new features. No need to send out a survey, your customers are already talking.
  • Measure Campaign Performance: See if your message is landing the way you intended. Did your ad campaign spark positive buzz or unexpected backlash?
  • Spot a Crisis Before It Happens: A sudden spike in negative sentiment can be an early warning sign of a brewing PR issue, giving you time to react before it snowballs.
  • Analyze Competitors: Turn your sentiment analysis tool on your competitors. Find out what customers love about them (and what they complain about) to identify gaps in the market.

Doing this manually is impossible. But with Python, you can automate the entire process and get clear, quantitative results that help you make smarter marketing decisions.

Step 1: Get Your Python Environment Ready

Before you can start analyzing tweets, you need to install a few essential Python libraries. These will handle everything from connecting to the X API to processing the text and running the sentiment analysis. If you don't have these installed, just open your terminal or command prompt and run these commands:

Required Libraries:

  1. Tweepy: This is the most popular library for accessing the X API. It makes fetching tweets incredibly straightforward. pip install tweepy
  2. TextBlob: A simple library for processing textual data. Its sentiment analysis function is perfect for beginners and returns a polarity score (how positive or negative the text is) and a subjectivity score (how much of an opinion it is vs. a factual statement). pip install textblob
  3. Pandas: If you're working with data in Python, you need Pandas. It allows you to organize your collective data into a clean, easy-to-use table called a DataFrame. pip install pandas
  4. Matplotlib & Seaborn: These are for visualization. They help you turn your sentiment data into easy-to-understand charts and graphs. pip install matplotlib seaborn

Step 2: Getting Access to the X (Twitter) API

This is often the step where people get a little stuck, but don't worry, it's very manageable. To pull tweets programmatically, you need to get access credentials from the X Developer Platform. Here's a quick rundown of the process:

  1. Apply for a Developer Account: Go to the X Developer Platform and sign up for an account. You'll need to answer a few questions about what you plan to build. Be honest and clear - just say you're building a tool for social listening and sentiment analysis for marketing and research purposes.
  2. Create a New Project and App: Once approved, you'll be taken to your developer dashboard. You'll need to create a new "Project" and then create an "App" within that project. Give them descriptive names.
  3. Save Your Credentials: When you create your app, X will generate a set of keys and tokens for you. The most important one for this project is the Bearer Token. It's a key that gives you "read-only" access to the API, which is all you need to search for public tweets. Copy this token and save it somewhere secure. Treat it like a password!

Step 3: Let's Write Some Python Code!

Now for the fun part. We're going to write a script that connects to the X API, fetches tweets about a topic, cleans them up, performs sentiment analysis, and organizes the results.

Part 1: Connecting to the API

First, we'll import the libraries we installed and use your Bearer Token to authenticate with Tweepy. Create a new Python file (e.g., sentiment_analyzer.py) and add the following code.

import tweepy
import pandas as pd
import re
from textblob import TextBlob
import matplotlib.pyplot as plt
import seaborn as sns

# Replace with your own Bearer Token
BEARER_TOKEN = "YOUR_BEARER_TOKEN_GOES_HERE"

# Create a Tweepy client
client = tweepy.Client(BEARER_TOKEN)

Just replace "YOUR_BEARER_TOKEN_GOES_HERE" with the actual token you saved from the developer portal.

Part 2: Searching for and Collecting Tweets

Next, let's search for tweets. We'll specify a search query (what you want to look for) and tell Tweepy how many tweets we want to get. For this example, let's analyze the sentiment around the release of a fictional new phone, the "PixelDream Pro".

# The search query. You can use hashtags, keywords, or mentions.
# The "-is:retweet" part excludes retweets for cleaner data.
search_query = '"PixelDream Pro" lang:en -is:retweet'

# Fetch the tweets
try:
tweets = client.search_recent_tweets(query=search_query, tweet_fields=["created_at"], max_results=100)

if not tweets.data:
print("No tweets found for the query.")
else:
# Create a list to store the tweet data
tweet_data = []
for tweet in tweets.data:
tweet_data.append([tweet.id, tweet.created_at, tweet.text])

# Create a pandas DataFrame
df = pd.DataFrame(tweet_data, columns=['id', 'created_at', 'text'])
print(f"{len(df)} tweets collected.")
print(df.head())

except Exception as e:
print(f"An error occurred: {e}")

This code finds the 100 most recent English-language tweets that mention "PixelDream Pro" (and aren't retweets) and puts them into a Pandas DataFrame. We're also grabbing the creation date and ID just in case.

Part 3: Cleaning the Text for Better Analysis

Tweet text is messy. It contains usernames, hashtags, URLs, and other noise that can interfere with sentiment analysis. We need to clean it up. Let's create a simple function to handle this.

def clean_tweet_text(text):
'''
A function to clean the tweet text.
'''
text = re.sub(r'@[A-Za-z0-9_]+', '', text) # Remove mentions
text = re.sub(r'#', '', text) # Remove the '#' symbol
text = re.sub(r'RT : ', '', text) # Remove RT prefixes
text = re.sub(r'https?://\S+', '', text) # Remove URLs

return text

# Apply this function to our 'text' column
df['cleaned_text'] = df['text'].apply(clean_tweet_text)
print("\nDataFrame with cleaned text:")
print(df.head())

This function uses regular expressions (that's the re.sub part) to strip out common junk from tweets, leaving us with just the core message.

Part 4: Performing the Sentiment Analysis

Now that we have clean text, we can use TextBlob to analyze it. We'll create two functions: one to get the polarity score and one to classify the sentiment as positive, negative, or neutral based on that score.

# Function to get sentiment polarity
def get_sentiment(text):
blob = TextBlob(text)
return blob.sentiment.polarity

# Function to classify sentiment
def classify_sentiment(polarity):
if polarity > 0.1: # Thresholds can be adjusted
return 'Positive'
elif polarity < -0.1:
return 'Negative'
else:
return 'Neutral'

# Apply the functions to our DataFrame
df['polarity'] = df['cleaned_text'].apply(get_sentiment)
df['sentiment'] = df['polarity'].apply(classify_sentiment)

print("\nDataFrame with sentiment analysis:")
print(df[['cleaned_text', 'sentiment']].head())

TextBlob's polarity score ranges from -1 (very negative) to +1 (very positive). We are setting thresholds here: anything above 0.1 is considered positive, anything below -0.1 is negative, and everything in between is neutral. You can adjust these thresholds to fit your specific needs.

Step 4: Visualize Your Findings

Numbers in a table are great, but a chart is often more powerful, especially when you're sharing results with your team. Here's how to create a simple bar chart to show the breakdown of sentiments using Matplotlib and Seaborn.

# Set plot style
sns.set(style="darkgrid")

# Create a count plot of sentiment
plt.figure(figsize=(8, 6))
sns.countplot(x='sentiment', data=df, order=['Positive', 'Neutral', 'Negative'], palette='viridis')

# Add titles and labels
plt.title('Sentiment Analysis of "PixelDream Pro" Tweets', fontsize=16)
plt.xlabel('Sentiment Type', fontsize=12)
plt.ylabel('Number of Tweets', fontsize=12)

# Show the plot
plt.show()

# You can also print the exact counts
sentiment_counts = df['sentiment'].value_counts()
print("\nSentiment Distribution:")
print(sentiment_counts)

This code will generate a bar chart that instantly shows you the overall mood of a conversation. Was the "PixelDream Pro" launch met with applause, shrugs, or disappointment? Now you know.

Final Thoughts

In this guide, you learned how to harness Python to build a powerful tool for social listening. By connecting to the X API, collecting tweets, analyzing their emotional tone, and visualizing the results, you can move beyond vanity metrics and gain a real understanding of how your audience feels. This is a foundational skill that can transform how you approach your social media strategy.

Of course, gathering insights is just the first step. The real value comes from acting on what you find. Whether it’s responding to customer feedback, adjusting your content schedule based on what's resonating, or engaging with conversations in real-time, effective management is essential. At Postbase, we built our platform to simplify exactly that. We focus on a simple, visual content calendar, reliable scheduling for video and a unified inbox for comments and DMs, clearing away the management chaos so you can focus on building your brand with the insights you just learned how to uncover.

Spencer's spent a decade building products at companies like Buffer, UserTesting, and Bump Health. He's spent years in the weeds of social media management—scheduling posts, analyzing performance, coordinating teams. At Postbase, he's building tools to automate the busywork so you can focus on creating great content.

Other posts you might like

How to Add Social Media Icons to an Email Signature

Enhance your email signature by adding social media icons. Discover step-by-step instructions to turn every email into a powerful marketing tool.

Read more

How to Add an Etsy Link to Pinterest

Learn how to add your Etsy link to Pinterest and drive traffic to your shop. Discover strategies to create converting pins and turn browsers into customers.

Read more

How to Grant Access to Facebook Business Manager

Grant access to your Facebook Business Manager securely. Follow our step-by-step guide to add users and assign permissions without sharing your password.

Read more

How to Record Audio for Instagram Reels

Record clear audio for Instagram Reels with this guide. Learn actionable steps to create professional-sounding audio, using just your phone or upgraded gear.

Read more

How to Add Translation in an Instagram Post

Add translations to Instagram posts and connect globally. Learn manual techniques and discover Instagram's automatic translation features in this guide.

Read more

How to Optimize Facebook for Business

Optimize your Facebook Business Page for growth and sales with strategic tweaks. Learn to engage your community, create captivating content, and refine strategies.

Read more

Stop wrestling with outdated social media tools

Wrestling with social media? It doesn’t have to be this hard. Plan your content, schedule posts, respond to comments, and analyze performance — all in one simple, easy-to-use tool.

Schedule your first post
The simplest way to manage your social media
Rating