Sentiment analysis in Python can mean anything from a three-line lexicon lookup to a GPU-hosted transformer that scores 28 separate emotions. The right choice depends on your text (tweets or legal contracts?), your languages, your accuracy bar and how much infrastructure you are willing to run. This guide walks through the four approaches Python developers actually use — VADER, TextBlob, Hugging Face transformers and a hosted API — with runnable code for each, and an honest look at where each one breaks.
If you are new to the topic, start with What is sentiment analysis? for the concepts. If you already know you need more than positive vs. negative, read emotion detection vs. sentiment analysis alongside this one.
Four ways to do sentiment analysis in Python
Every Python sentiment tool falls into one of four buckets. They differ less in API ergonomics (all of them are a function call) than in what they understand:
- Lexicon + rules (VADER). A dictionary of words with hand-assigned valence, plus heuristics for negation, intensifiers and punctuation. Instant, deterministic, English-only.
- Lexicon + averaging (TextBlob). Similar idea with a simpler aggregation and an extra subjectivity score.
- Pretrained transformers (Hugging Face). Neural models that read the whole sentence in context. Much more accurate on real text, but heavier — you manage model downloads, memory and, ideally, a GPU.
- Hosted API. Someone else runs the transformer; you send text over HTTP. No model ops, pay per call, network latency.
Install what you need for the examples below:
pip install vaderSentiment textblob transformers torch pandas
# optional, for the hosted API example
pip install requestsVADER: fast rule-based scoring
VADER (Valence Aware Dictionary and sEntiment Reasoner) was built for social-media text. It looks up each token in a lexicon of roughly 7,500 human-rated terms (including emoticons and slang), then adjusts scores with rules: ALL CAPS and exclamation marks amplify, words like "extremely" boost, "kind of" dampens, negations flip, and a contrastive "but" shifts weight to the clause after it.
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
for text in [
"The battery life is great.",
"The battery life is GREAT!!!",
"The battery life is not great.",
"The screen is nice, but the battery is awful.",
]:
scores = analyzer.polarity_scores(text)
print(f"{scores['compound']:+.3f} {text}")polarity_scores returns a dict with four keys: neg, neu and pos (the proportions of the text that fall in each bucket, summing to about 1) and compound, a normalized score in [-1, 1]. The conventional thresholds are compound ≥ 0.05 for positive, ≤ -0.05 for negative, and neutral in between.
NLTK ships the same algorithm, so if NLTK is already in your stack you can skip the extra dependency:
import nltk
nltk.download("vader_lexicon") # one-time
from nltk.sentiment.vader import SentimentIntensityAnalyzer
sia = SentimentIntensityAnalyzer()
print(sia.polarity_scores("I can't believe how good this is!"))When VADER is enough: English tweets, chat messages, short reviews, quick exploratory analysis, or a baseline to beat. When it is not: sarcasm, domain jargon ("the stock is killing it"), long documents, and any language other than English. We cover the details in VADER sentiment analysis explained.
TextBlob: polarity and subjectivity
TextBlob wraps a pattern-based lexicon and exposes two numbers per text: polarity in [-1, 1] and subjectivity in [0, 1], where 0 is very objective and 1 is very subjective.
from textblob import TextBlob
blob = TextBlob("The hotel was clean but the staff were incredibly rude.")
print(blob.sentiment) # Sentiment(polarity=..., subjectivity=...)
print(blob.sentiment.polarity)
# Sentence-level scores are often more useful than one document score
for sentence in blob.sentences:
print(f"{sentence.sentiment.polarity:+.2f} {sentence}")Subjectivity is TextBlob's main differentiator: it helps you filter out factual statements ("The package arrived on Tuesday") before aggregating opinion. In practice its polarity is less robust than VADER's on informal text, and it shares the same fundamental limits: English-only, no real understanding of context. Splitting into sentences, as above, is a cheap trick that improves both tools on mixed reviews.
Hugging Face transformers for sentiment
Transformer models read each word in the context of every other word, which is exactly what lexicon methods cannot do. "Not bad at all", "I expected to hate it" and "great, another delay" are routine for a fine-tuned transformer and traps for a lexicon.
from transformers import pipeline
# Default English sentiment model: a DistilBERT fine-tuned on SST-2
clf = pipeline("sentiment-analysis")
print(clf([
"Not bad at all, honestly.",
"Great, another two-hour delay.",
]))
# [{'label': 'POSITIVE', 'score': ...}, {'label': 'NEGATIVE', 'score': ...}]A few practical notes that save hours:
- Pin the model. Calling
pipeline("sentiment-analysis")without amodel=argument prints a warning and picks a default (currentlydistilbert-base-uncased-finetuned-sst-2-english). Pass the model name explicitly in production so upgrades never change your numbers silently. - Binary output. The SST-2 model has no neutral class; everything is POSITIVE or NEGATIVE with a confidence. Neutral text will be forced into one side, so threshold on
scoreif you need a neutral bucket. - Truncation. BERT-family models have a 512-token context. Pass
truncation=Truefor long inputs, or split documents into chunks and aggregate. - Batching and GPU. Pass a list of texts and
batch_size=32, anddevice=0to use the first CUDA GPU. On CPU expect tens of milliseconds per short text; on GPU, thousands of texts per second are realistic.
Multi-label emotion models in Python
Positive vs. negative throws away most of what text says. A support ticket that is confused needs a different response from one that is angry, even though both are "negative". Emotion models trained on Google's GoEmotions dataset score 27 emotions plus neutral (see the full list of 28 emotions).
from transformers import pipeline
emo = pipeline(
"text-classification",
model="SamLowe/roberta-base-go_emotions", # English GoEmotions model
top_k=None, # return all 28 labels
)
result = emo("Thanks so much, I was really worried this wouldn't arrive in time!")[0]
for item in sorted(result, key=lambda r: r["score"], reverse=True)[:5]:
print(f"{item['label']:<15} {item['score']:.3f}")That RoBERTa model is English-only. For other languages you need a multilingual backbone such as mBERT or XLM-R fine-tuned on translated or native emotion data — the model behind our API, AnasAlokla/multilingual_go_emotions_V1.1, is an mBERT GoEmotions classifier covering Arabic, English, French, Spanish, German and Turkish. See multilingual sentiment analysis for the trade-offs.
Sentiment analysis API in Python (hosted)
Running transformers yourself is straightforward in a notebook and considerably less so in production: model downloads, GPU drivers, autoscaling, batching, cold starts. A hosted sentiment analysis API moves that work to someone else in exchange for a per-request price and network latency.
The Sentiment API returns all 28 GoEmotions scores, the top emotion and a valence score in [-1, 1] for each message. You send an API key with each request and pay from prepaid credit. Jobs are asynchronous — you submit, get a job_id, and poll. Here is a condensed Python client (the full version with error handling is in the API docs):
# pip install requests
import os, time, requests
HOST = "https://emotions.togoder.click"
HEADERS = {"Authorization": f"Bearer {os.environ['SENTIMENT_API_KEY']}"}
def call(method: str, path: str, body: dict | None = None) -> dict:
r = requests.request(method, HOST + path, json=body, headers=HEADERS)
r.raise_for_status()
return r.json()
job = call("POST", "/api/analyze", {"text": "Je suis tellement soulagé, merci !"})
while True:
res = call("GET", f"/api/jobs/{job['job_id']}")
if res["status"] not in ("queued", "processing"):
break
time.sleep(1)
r = res["result"]
print(r["top_emotion"], r["top_score"], r["valence"])
for p in r["predictions"][:5]: # sorted by score, all 28 present
print(p["label"], round(p["score"], 3))For volume, POST /api/analyze/batch takes up to 10,000 texts in one request with a single debit; each text becomes its own job. Pricing is per message and tracks real GPU cost — at the time of writing roughly $0.00089 per message up to 256 characters; the pricing page shows the live number.
Honest trade-offs: polling adds a second or more of latency, so this is a poor fit for per-keystroke UI; inputs beyond ~512 tokens are truncated by the model; and you pay in advance from prepaid credit, with a $10 minimum top-up.
Comparison: which Python approach to pick
| Approach | Output | Languages | Speed | Best for |
|---|---|---|---|---|
| VADER | neg/neu/pos + compound [-1,1] | English | Microseconds, CPU | Tweets, chat, quick baselines |
| TextBlob | polarity [-1,1], subjectivity [0,1] | English | Microseconds, CPU | Filtering objective text, teaching |
| HF sentiment model | Label + confidence (often binary) | Model-dependent | ms per text; GPU helps | Accurate polarity at scale, self-hosted |
| HF emotion model | 28 emotion scores (multi-label) | Model-dependent | ms per text; GPU helps | Why people feel what they feel |
| Hosted emotion API | 28 emotions + valence | 6 languages (Sentiment API) | Async, ~seconds | No infra, multilingual, bursty volume |
A pragmatic path many teams follow: start with VADER to explore the data, switch to a transformer once you see VADER's mistakes on your domain, and decide between self-hosting and an API based on volume and how much you value not running GPUs. Our sentiment analysis tools comparison covers cloud NLP APIs as well.
Scoring a pandas DataFrame
Most real work starts with a CSV. Here is the pattern for adding sentiment columns to a DataFrame efficiently with each approach:
import pandas as pd
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from transformers import pipeline
df = pd.read_csv("reviews.csv") # expects a "text" column
df["text"] = df["text"].fillna("").astype(str)
# VADER: row-wise is fine, it's very fast
vader = SentimentIntensityAnalyzer()
df["vader_compound"] = df["text"].map(lambda t: vader.polarity_scores(t)["compound"])
df["vader_label"] = pd.cut(
df["vader_compound"], bins=[-1.01, -0.05, 0.05, 1.01],
labels=["negative", "neutral", "positive"],
)
# Transformers: always pass a list and batch, never call row-by-row
clf = pipeline("sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english",
truncation=True)
preds = clf(df["text"].tolist(), batch_size=64)
df["hf_label"] = [p["label"] for p in preds]
df["hf_score"] = [p["score"] for p in preds]
print(df.groupby("vader_label")["hf_label"].value_counts())Comparing two methods side by side like this is an excellent way to find the disagreements — and reading those rows teaches you more about your data than any accuracy number. For a full pipeline on reviews, see sentiment analysis of customer reviews.
Evaluating accuracy on your own data
Published benchmark numbers rarely transfer to your domain. Before you trust any tool, label a small sample yourself:
- Randomly sample 200–500 texts from your real data (not the easy ones).
- Have two people label them independently with the same guidelines; measure their agreement. If humans agree only 75% of the time, no model will reach 95%.
- Run each candidate and compute per-class precision and recall with
sklearn.metrics.classification_report, not just accuracy — class imbalance hides failures. - Read 30 errors per model. Patterns (sarcasm, product names, a language you forgot about) tell you what to fix.
from sklearn.metrics import classification_report
gold = df_labeled["gold"] # your human labels
pred = df_labeled["vader_label"] # or hf_label, api_label…
print(classification_report(gold, pred, digits=3))If you need public data to benchmark against, see our list of sentiment analysis datasets.
Frequently asked questions
What is the easiest way to do sentiment analysis in Python?
For English text, VADER is the easiest: pip install vaderSentiment, create a SentimentIntensityAnalyzer and call polarity_scores(text). It needs no training data, no GPU and runs in microseconds per sentence. For higher accuracy on longer or more nuanced text, use a Hugging Face transformers pipeline or a hosted sentiment analysis API.
Is VADER or TextBlob better for sentiment analysis?
VADER is usually the better default for short, informal English text such as tweets, chat messages and reviews, because its lexicon and heuristics handle capitalization, punctuation, emoticons, intensifiers and negation. TextBlob is simple and adds a subjectivity score, but its polarity is less sensitive to informal language. Both are rule-based and English-only.
Which Python library gives the most accurate sentiment analysis?
Transformer models fine-tuned for sentiment or emotion (available through the Hugging Face transformers library) are generally far more accurate than lexicon methods on real-world text, because they read words in context and handle negation, contrast and sarcasm better. The trade-off is that they are slower and benefit from a GPU.
Can I do sentiment analysis in Python for languages other than English?
Yes, but not with VADER or TextBlob, which are English-only. Use a multilingual transformer model (for example an mBERT- or XLM-R-based classifier) or a hosted API that supports your languages. The Sentiment API supports Arabic, English, French, Spanish, German and Turkish without a language parameter.
How do I get emotions instead of just positive or negative in Python?
Use a multi-label emotion classifier trained on a taxonomy such as GoEmotions. In transformers, load the model with pipeline('text-classification', model=..., top_k=None) to get a score for every label. Because GoEmotions is multi-label, scores come from a sigmoid and do not sum to 1; apply a per-label threshold rather than taking only the argmax.