---
title: "Review Sentiment Analysis in Python | ScrapeReviews"
description: "Analyse customer review sentiment in Python: a star-rating baseline, VADER, a transformer model, then an LLM that extracts aspects. With code and costs."
url: "https://scrapereviews.com/blog/review-sentiment-analysis-python"
markdown: "https://scrapereviews.com/blog/review-sentiment-analysis-python.md"
published: "2026-11-25"
updated: "2026-11-25"
---

# Customer review sentiment analysis in Python: from star ratings to aspects

Published 2026-11-25 · Updated 2026-11-25 · By ScrapeReviews

Reviews are the most honest product feedback most companies get, and there is usually too much of it to read. Sentiment analysis turns thousands of texts into numbers you can chart and, done well, into a list of the specific things customers love or hate. This guide builds that pipeline in Python in four steps of increasing power and cost, using real Trustpilot reviews as the data.

## Step 1: get the reviews

Any review source works, but you need text, a rating and a date. Here we use the Trustpilot reviews endpoint of ScrapeReviews, `GET /v1/companies/{domain}/reviews`, which returns up to 20 reviews per call with an `X-API-Key` header. [Sign up for free](https://scrapereviews.com/auth/sign-up) and create a key in the dashboard under API keys. A quick look from any language:

```bash title="cURL"
curl "https://api.scrapereviews.com/v1/companies/www.example.com/reviews?language=en&limit=20" \
  -H "X-API-Key: YOUR_API_KEY"
```

```python title="Python"
import requests

page = requests.get(
    "https://api.scrapereviews.com/v1/companies/www.example.com/reviews",
    headers={"X-API-Key": "YOUR_API_KEY"},
    params={"language": "en", "limit": 20},
    timeout=60,
).json()
print(page["data"][0]["rating"], page["data"][0]["text"][:80])
```

```javascript title="JavaScript"
const resp = await fetch("https://api.scrapereviews.com/v1/companies/www.example.com/reviews?language=en&limit=20", {
  headers: { "X-API-Key": process.env.SCRAPEREVIEWS_API_KEY },
});
const page = await resp.json();
console.log(page.data[0].rating, page.data[0].text.slice(0, 80));
```

For the analysis we want all of them in a pandas DataFrame, following `meta.next_cursor` until it is `null`:

```python
import os
import pandas as pd
import requests

def fetch_all(domain, **filters):
    params, rows = {"limit": 20, **filters}, []
    while True:
        resp = requests.get(f"https://api.scrapereviews.com/v1/companies/{domain}/reviews", params=params,
                            headers={"X-API-Key": os.environ["SCRAPEREVIEWS_API_KEY"]}, timeout=60)
        resp.raise_for_status()
        page = resp.json()
        rows += page["data"]
        if not page["meta"]["next_cursor"]:
            return pd.DataFrame(rows)
        params["cursor"] = page["meta"]["next_cursor"]

df = fetch_all("www.example.com", language="en", since="2026-01-01")
df["published_at"] = pd.to_datetime(df["published_at"])
df["text_full"] = df["title"].fillna("") + ". " + df["text"].fillna("")
print(len(df), "reviews")
```

Filtering on `language=en` keeps step 2 honest, since the English lexicon would misread other languages. Pagination and the other filters are covered in [how to scrape Trustpilot reviews](https://scrapereviews.com/blog/how-to-scrape-trustpilot-reviews.md); if you would rather start from a spreadsheet, [export the reviews to CSV](https://scrapereviews.com/blog/export-trustpilot-reviews-to-csv.md) and load it with `pd.read_csv`.

## Step 2: the star rating is your baseline

Before any model, use the label the reviewer gave you. Map 1 and 2 stars to negative, 3 to neutral and 4 and 5 to positive, then look at the trend:

```python
df["stars_label"] = pd.cut(df["rating"], bins=[0, 2, 3, 5], labels=["negative", "neutral", "positive"])
monthly = df.set_index("published_at").resample("MS")["rating"].agg(["mean", "count"])
print(monthly.tail(6))
print(df["stars_label"].value_counts(normalize=True).round(2))
```

This is free, instant and already answers "are we getting better or worse?". Its limits are what the next steps fix: a 3-star review can be furious about delivery and delighted with the product, and a rating says nothing about why.

## Step 3: a lexicon and a transformer model

**VADER** (`pip install vaderSentiment`) scores text with a hand-built English lexicon plus rules for negation, capitals and punctuation. It runs on a laptop CPU at thousands of reviews per second:

```python
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

vader = SentimentIntensityAnalyzer()
df["vader"] = df["text_full"].map(lambda t: vader.polarity_scores(t)["compound"])  # -1 to 1
```

**A pretrained transformer** is noticeably better on sarcasm, negation and long texts. The Hugging Face `transformers` pipeline downloads a model fine-tuned for sentiment; `cardiffnlp/twitter-roberta-base-sentiment-latest` returns negative, neutral or positive:

```python
from transformers import pipeline

clf = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment-latest")
preds = clf(df["text_full"].tolist(), batch_size=32, truncation=True)
df["model_label"] = [p["label"] for p in preds]
df["model_score"] = [p["score"] for p in preds]
```

For reviews in several languages, a multilingual model such as `nlptown/bert-base-multilingual-uncased-sentiment`, which predicts 1 to 5 stars directly, is a good alternative.

Now the useful trick: **compare the model with the stars**. Reviews where they disagree are exactly the ones worth reading.

```python
mismatch = df[(df["stars_label"] == "positive") & (df["model_label"] == "negative")]
print(len(mismatch), "positive ratings with a negative text")
print(mismatch[["rating", "text_full"]].head(10).to_string())
```

In practice these are often "great product, but..." reviews, where the "but" is the real feedback.

## Step 4: aspects with an LLM

Sentiment scores tell you how people feel. Aspect-based analysis tells you about what: shipping, price, support, product quality, the app. Large language models do this well with no training data. Here is a version with the Anthropic Python SDK (`pip install anthropic`, key in `ANTHROPIC_API_KEY`) that sends 20 reviews per request and asks for JSON that matches a schema, so the output can be parsed without guesswork:

```python
import json
import anthropic

client = anthropic.Anthropic()

SCHEMA = {
    "type": "object",
    "properties": {
        "reviews": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "id": {"type": "string"},
                    "aspects": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "aspect": {"type": "string", "enum": ["delivery", "price", "product quality",
                                           "customer service", "website or app", "returns and refunds", "other"]},
                                "sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
                                "quote": {"type": "string"},
                            },
                            "required": ["aspect", "sentiment", "quote"],
                            "additionalProperties": False,
                        },
                    },
                },
                "required": ["id", "aspects"],
                "additionalProperties": False,
            },
        }
    },
    "required": ["reviews"],
    "additionalProperties": False,
}

def extract_aspects(batch):
    reviews = [{"id": r["id"], "rating": int(r["rating"]), "text": r["text_full"]} for r in batch]
    response = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=16000,
        system="You analyse customer reviews. For each review, list the aspects it mentions, the sentiment "
               "about each one and a short quote from the review that supports it. Use only the given aspects.",
        messages=[{"role": "user", "content": json.dumps(reviews)}],
        output_config={"effort": "low", "format": {"type": "json_schema", "schema": SCHEMA}},
    )
    text = next(b.text for b in response.content if b.type == "text")
    return json.loads(text)["reviews"], response.usage

records = df.to_dict("records")
rows = []
for i in range(0, len(records), 20):
    results, usage = extract_aspects(records[i:i + 20])
    rows += [{"id": r["id"], **a} for r in results for a in r["aspects"]]

aspects = pd.DataFrame(rows)
print(pd.crosstab(aspects["aspect"], aspects["sentiment"]))
```

The final table is what a product team actually wants: for each aspect, how many positive, neutral and negative mentions, with a quote to back each one. Merge `aspects` with `df` on `id` and you can chart negative delivery mentions per month, or compare aspects across competitors.

A few choices in that code are deliberate:

- **A fixed list of aspects** (the `enum`) makes results countable. Free-form aspects produce "shipping", "delivery" and "postage" as three different things.
- **The quote** makes every label checkable: when a number looks surprising, you can read why.
- **Low effort** is enough for extraction; save higher effort for summaries that need reasoning.
- **Model choice:** we used `claude-opus-5-5`. For high volumes, a smaller model such as `claude-haiku-5-5` is far cheaper and is worth testing against a sample you labelled by hand.

## What it costs, honestly

The reviews themselves: one API call per 20 reviews at $8 per 1,000 calls, so 10,000 reviews are 500 calls, about $4, and the first 30 calls each month are free ([pricing](https://scrapereviews.com/pricing.md)).

Steps 2 and 3 cost only compute: VADER is instant, and the transformer handles thousands of reviews in minutes on a CPU and much faster on a GPU.

Step 4 is where the bill can grow, so estimate before you run. A batch of 20 average reviews is roughly 2,000 to 3,000 input tokens and under 1,000 output tokens, plus any reasoning tokens the model produces. Multiply those by the per-token prices of the model you pick: the large model costs many times more than the small one, so test the small one first. Check Anthropic's pricing page for the current prices, and read `response.usage` on a first batch of real data to see your actual numbers.

Two ways to spend less:

- **Batch, in both senses.** Sending 20 reviews per request shares the system prompt across them. And Anthropic's Message Batches API (`client.messages.batches.create`) processes requests asynchronously at half price, usually within an hour, which suits a nightly job.
- **Analyse only what changed.** Store results by review `id` and fetch new reviews with `since`. A daily run then costs one reviews call and a handful of tokens per company.

## Putting it to work

The same pipeline, run every week across your brand and three rivals, becomes a competitive dashboard: see [competitor review monitoring](https://scrapereviews.com/blog/competitor-review-monitoring.md) for that setup. All endpoints and filters are in [the API reference](https://scrapereviews.com/docs/api.md), and [the reviews API page](https://scrapereviews.com/trustpilot-reviews-api.md) has an overview.

ScrapeReviews is an independent service, not affiliated with Trustpilot. [Create a free account](https://scrapereviews.com/auth/sign-up) to get 30 calls a month, no card required, and follow [the docs](https://scrapereviews.com/docs.md) to fetch your first reviews in a minute.

## Frequently asked questions

### Do I need sentiment analysis if reviews already have star ratings?

For an overall score, the star rating is usually enough. Sentiment models earn their place on mixed reviews, on texts without a rating and above all for aspect analysis, which tells you what people are happy or unhappy about rather than how much.

### Which Python library is best for review sentiment?

VADER is fast and needs no GPU but only handles English well. A pretrained transformer from Hugging Face is more accurate and handles negation better. A large language model is the most flexible, because it can extract aspects and reasons, at a cost per review.

### How much does it cost to analyse 10,000 reviews with an LLM?

It depends on the model and the length of the reviews. With 20 reviews per request, a small model costs well under a dollar for 10,000 reviews, a large one roughly 10 to 20 dollars, and the batch API halves either figure. Measure on a sample of your own data before running everything.

### Does sentiment analysis work on reviews in other languages?

Lexicons such as VADER are built for English. Multilingual transformer models and large language models handle many languages, and you can filter reviews by language in the API request to analyse each language separately.

## Related guides

- [How to export Trustpilot reviews to CSV (Python, pandas and Node.js)](https://scrapereviews.com/blog/export-trustpilot-reviews-to-csv.md): Export all Trustpilot reviews of a company to a CSV that opens cleanly in Excel and Google Sheets, with Python, pandas or Node.js, and keep it up to date.
- [How to scrape Trustpilot reviews (with cURL, Python and JavaScript)](https://scrapereviews.com/blog/how-to-scrape-trustpilot-reviews.md): Scrape Trustpilot reviews without fighting a WAF: one API call per 20 reviews, cursor pagination, filters by stars, language and date, Python and JS code.
- [Competitor review monitoring: track rivals on Trustpilot with Python](https://scrapereviews.com/blog/competitor-review-monitoring.md): Track competitors on Trustpilot: rating trend, review volume, reply rate and complaint themes, with a Python script that alerts you when something drops.
