How-to

Google Reviews Sentiment Analysis with Python

Collect Google Maps reviews with an API, then score sentiment, find recurring complaints and track ratings over time with pandas and a little Python.

Updated 8 min readBy the ScrapeMapsAPI team

Star ratings tell you how satisfied customers are; review text tells you why. Sentiment analysis of Google reviews turns hundreds or thousands of free-text reviews into numbers you can track: how positive each review really is, which topics come up in the angry ones, and whether things are getting better or worse month by month. With Python it takes three steps: collect the reviews, score them, and aggregate the scores by topic and by time.

This guide walks through all three with working code. We collect every review of a place with the Google Maps Reviews API, score sentiment with VADER (a small, fast, rule-based model that needs no GPU), then use pandas to find recurring complaints and plot the trend. At the end we look at when to swap VADER for a transformer model.

Setup

You need Python 3.9 or newer and four packages:

Terminal
pip install requests pandas vaderSentiment matplotlib
export SCRAPEMAPSAPI_API_KEY="key_your_api_key"

The API key comes from the dashboard after you sign up; the first 200 calls every month are free, and each call returns a page of up to 20 reviews, so a place with 2,000 reviews takes about 100 calls.

You also need the place's identifier. The reviews endpoint accepts a ChIJ place ID, a CID or a feature ID. If all you have is a Google Maps link, the resolve endpoint converts it; our explainer on place IDs, CIDs and feature IDs covers the details.

Step 1: collect the reviews

The reviews endpoint returns one page per call. You follow pagination.next_cursor until pagination.has_more is false. Two parameters matter for sentiment work:

  • language=en asks for English output. For every review written in another language, Google's translation comes back in translated_text, next to the original in text. That lets an English-only model like VADER score reviews written in Italian, German or Japanese.
  • sort=newest makes the order chronological, which is convenient when you only want reviews after a date.
Python
import os
import time
import requests
import pandas as pd

API = "https://api.scrapemapsapi.com/v1"
HEADERS = {"X-API-Key": os.environ["SCRAPEMAPSAPI_API_KEY"]}
PLACE = "ChIJ8cLgoQNUKhMReGlaTjwrH40"


def get(path, params):
    while True:
        r = requests.get(f"{API}{path}", headers=HEADERS, params=params, timeout=60)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "30")))
            continue
        if r.status_code != 200:
            raise RuntimeError(f"{r.status_code}: {r.json()['detail']}")
        return r.json()


def all_reviews(place, max_pages=200):
    params = {"sort": "newest", "language": "en", "limit": 20}
    for _ in range(max_pages):
        page = get(f"/places/{place}/reviews", params)
        yield from page["data"]
        if not page["pagination"]["has_more"]:
            return
        params = {"cursor": page["pagination"]["next_cursor"]}


rows = []
for r in all_reviews(PLACE):
    rows.append({
        "id": r["id"],
        "rating": r["rating"],
        "published_at": r["published_at"],
        "language": r["language"],
        "text": r["translated_text"] or r["text"],
        "original": r["text"],
        "author": r["author"]["id"],
        "replied": r["owner_response"] is not None,
    })

df = pd.DataFrame(rows)
df["published_at"] = pd.to_datetime(df["published_at"], utc=True)
df.to_csv("reviews.csv", index=False)
print(len(df), "reviews")

The cursor already carries the sort and language, so later calls only send cursor. The max_pages cap protects your credits if something goes wrong. The full parameter list is in the API reference, and a longer walkthrough of the collection step, CSV export included, is in scrape Google Maps reviews with Python.

Two notes on the data. Authors are a pseudonymous, stable ID: you can count how many reviews one author left, but there are no names or profile links, by design. And many Google reviews are rating-only, with text set to null; keep them for rating statistics but drop them before scoring text.

Step 2: score sentiment with VADER

VADER (Valence Aware Dictionary and sEntiment Reasoner) was built for short, informal text like social posts and reviews. It understands intensifiers ("very good"), negation ("not good"), capitals and exclamation marks, and returns a compound score from -1 (very negative) to +1 (very positive). It runs on a laptop at thousands of reviews per second.

Python
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

analyzer = SentimentIntensityAnalyzer()
texts = df.dropna(subset=["text"]).copy()
texts["sentiment"] = texts["text"].map(lambda t: analyzer.polarity_scores(t)["compound"])


def label(score):
    if score >= 0.05:
        return "positive"
    if score <= -0.05:
        return "negative"
    return "neutral"


texts["label"] = texts["sentiment"].map(label)
print(texts["label"].value_counts(normalize=True).round(2))

The 0.05 thresholds are the ones VADER's authors recommend. Before trusting the scores, check them against the stars:

Python
print(texts.groupby("rating")["sentiment"].agg(["mean", "count"]).round(2))

You should see the mean sentiment rise steadily from 1 to 5 stars. The interesting rows are the disagreements: 5-star reviews with negative text ("great food but the wait was awful") and 1-star reviews with mild text. Those mixed reviews are where the specific, fixable problems are hiding.

Python
mixed = texts[(texts["rating"] >= 4) & (texts["sentiment"] < -0.2)]
for t in mixed["text"].head(10):
    print("-", t[:200])

Step 3: find recurring complaints

A sentiment score says a review is negative; it does not say what about. The simplest topic method that works well on reviews is a keyword map: list the aspects that matter for the business and the words customers use for them, then measure the sentiment of reviews mentioning each aspect.

Python
ASPECTS = {
    "wait": ["wait", "waited", "slow", "queue", "line", "took forever"],
    "staff": ["staff", "waiter", "waitress", "rude", "friendly", "service"],
    "price": ["price", "expensive", "overpriced", "cheap", "value", "bill"],
    "food": ["food", "dish", "taste", "cold", "delicious", "portion"],
    "cleanliness": ["dirty", "clean", "toilet", "bathroom", "smell"],
    "booking": ["reservation", "booking", "booked", "table"],
}

lower = texts["text"].str.lower()
summary = []
for aspect, words in ASPECTS.items():
    mask = lower.str.contains("|".join(words), regex=True)
    subset = texts[mask]
    summary.append({
        "aspect": aspect,
        "mentions": len(subset),
        "share_negative": round((subset["label"] == "negative").mean(), 2) if len(subset) else None,
        "avg_sentiment": round(subset["sentiment"].mean(), 2) if len(subset) else None,
    })

print(pd.DataFrame(summary).sort_values("share_negative", ascending=False).to_string(index=False))

Sorted by the share of negative mentions, the top rows are the problems worth fixing. Keyword maps are crude (a review mentioning "line" might be about a phone line), but they are transparent, fast to adjust and good enough to rank issues. For restaurants, the details field of each review also holds structured answers such as food, service and atmosphere ratings when the reviewer gave them, which you can average directly.

Step 4: track the trend over time

The question managers actually ask is "is it getting better?". Resample by month:

Python
import matplotlib.pyplot as plt

monthly = texts.set_index("published_at").resample("MS").agg(
    reviews=("id", "count"), sentiment=("sentiment", "mean"), stars=("rating", "mean")
)
monthly = monthly[monthly["reviews"] >= 5]  # months with too few reviews are noise

ax = monthly["sentiment"].plot(label="sentiment (VADER)")
monthly["stars"].div(5).plot(ax=ax, label="stars / 5")
ax.legend()
plt.title("Review sentiment per month")
plt.savefig("sentiment-trend.png", dpi=150)

Dropping months with fewer than five reviews avoids reading meaning into one angry customer. A dip that lines up with a menu change, a new manager or a renovation is the kind of finding this chart exists for.

Comparing several places

The same pipeline works across locations of a chain or across competitors: collect the reviews of each place, add a place column and group by it. Comparing the aspect table between your location and the top-rated competitor shows where they win. Our guide to local SEO competitor analysis shows how to find those competitors from a Google Maps search.

When to use a transformer model instead

VADER is a dictionary model: it misses sarcasm, domain-specific phrases and context. If you need better accuracy, or want to score reviews in their original language instead of the translation, use a pretrained transformer:

Terminal
pip install transformers torch
Python
from transformers import pipeline

clf = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
sample = texts["original"].head(200).tolist()
stars = [int(p["label"][0]) for p in clf(sample, truncation=True)]

This multilingual model predicts 1 to 5 stars directly from text in English, German, French, Spanish, Italian and Dutch. It is slower than VADER (seconds per hundred reviews on a CPU) and the download is several hundred megabytes, so it pays off when accuracy matters more than speed. A practical approach: use VADER for dashboards and trends, a transformer for the deep dive.

What it costs

Every successful call costs 1 credit and returns up to 20 reviews. 1,000 reviews take 50 calls; 10,000 reviews take 500 calls, $1.50 at the list price of $3 per 1,000 calls, and less with credit packs (see pricing). Errors are never billed. The analysis itself is free: it runs on your machine. To keep scores current without re-downloading everything, rerun the collection with sort=newest and stop at the first review ID you already have; our Node.js review monitor uses exactly that pattern.

FAQ

What is the best Python library for Google review sentiment analysis?

For speed and simplicity, VADER (the vaderSentiment package) works well on short, informal review text and needs no GPU. For higher accuracy or reviews in several languages, a pretrained transformer such as nlptown/bert-base-multilingual-uncased-sentiment, run with the Hugging Face transformers pipeline, predicts a 1 to 5 star score from the text.

Can I analyse Google reviews written in other languages?

Yes. Request the reviews with language=en and the API returns Google's English translation in translated_text for every review written in another language, next to the original text. You can score the translations with an English model, or score the originals with a multilingual transformer.

How do I get all Google reviews of a place for analysis?

Call the reviews endpoint with the place ID and follow the cursor in pagination.next_cursor until has_more is false. Each call returns up to 20 reviews and costs 1 credit, so a place with 2,000 reviews needs about 100 calls. The official Google Places API returns at most 5 reviews per place, which is not enough for analysis.

How do I find what customers complain about in reviews?

Score each review's sentiment, then group reviews by aspect using a keyword list per topic, such as wait times, staff, price, food and cleanliness. Sorting the aspects by the share of negative mentions shows which problems come up most often. Reviews with high stars but negative text are often the most specific.

Why does the sentiment score not match the star rating?

Star ratings and text often disagree: a 4-star review can describe one serious problem, and a 1-star review can be short and mild. Dictionary models also miss sarcasm and context. Comparing the average sentiment per star rating is a good sanity check, and the disagreements are usually worth reading by hand.

Try it on your own data

Create a free account and get 200 free API calls every month. No credit card required.

Related articles