Azure · Cloud Computing

Sentiment Analysis with Azure Text Analytics (Azure Language) in Python

Run sentiment analysis and opinion mining on customer reviews with Azure Language's Python SDK, and when we'd use a Foundry model instead.

·4 min read
On this page

Say you run a restaurant group, you’ve just changed the menu, and you have a few thousand reviews to read. You want to know what people dislike, not just whether they’re unhappy. That’s what this post walks through, using Azure’s sentiment analysis API from Python.

Some naming first. Text Analytics became part of the Language service, which is now called Azure Language in Foundry Tools. The Python package is still azure-ai-textanalytics (5.4.0 at the time of writing), and the client is still TextAnalyticsClient, so old tutorials mostly line up.

One thing to know before you build on it: sentiment analysis and opinion mining retire from Azure Language on 31 March 2029. Microsoft is pointing new projects to Foundry models. Existing workloads have time, but if you’re starting fresh, read the last section before you commit.

Setup

You need a Language resource, or a Foundry resource, which includes Language. Copy the endpoint and a key from Keys and Endpoint in the portal into two environment variables, LANGUAGE_ENDPOINT and LANGUAGE_KEY. Then install the packages:

pip install azure-ai-textanalytics pandas

If you’d rather not use keys, DefaultAzureCredential from azure-identity works too. It needs a resource with a custom subdomain and the Cognitive Services User role (or a narrower Language role) on your identity.

Don’t “clean” the text

The original version of this post lowercased everything and stripped every character that wasn’t a-z, 0-9 or a period before sending it. Please don’t. The model reads punctuation, casing and emphasis. “NOT good!!!” and “not good” don’t carry the same signal, and that regex also mangled accented characters in Spanish and French reviews. Trim whitespace and drop empty rows, and leave the rest alone.

Score the reviews

The old code also made one API call per review. The sentiment endpoint accepts up to 10 documents per request, and each document can be up to 5,120 characters, so batching cuts the number of calls by 10x. We also turn on opinion mining. Opinion mining is what tells you what people are negative about (“portion”, “salsa”) rather than just that the review was negative.

import os

import pandas as pd
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

client = TextAnalyticsClient(
    endpoint=os.environ["LANGUAGE_ENDPOINT"],
    credential=AzureKeyCredential(os.environ["LANGUAGE_KEY"]),
)

df = pd.read_csv("customer_reviews.csv")  # one review per row, in a "text" column
texts = df["text"].dropna().astype(str).str.strip()
texts = texts[texts != ""].tolist()

rows = []
for start in range(0, len(texts), 10):  # sentiment accepts 10 documents per request
    batch = texts[start:start + 10]
    results = client.analyze_sentiment(batch, language="en", show_opinion_mining=True)
    for text, doc in zip(batch, results):
        if doc.is_error:
            rows.append({"text": text, "sentiment": "error", "targets": doc.error.message})
            continue
        targets = [
            f"{opinion.target.text.lower()}:{opinion.target.sentiment}"
            for sentence in doc.sentences
            for opinion in sentence.mined_opinions
        ]
        rows.append({
            "text": text,
            "sentiment": doc.sentiment,
            "positive": doc.confidence_scores.positive,
            "neutral": doc.confidence_scores.neutral,
            "negative": doc.confidence_scores.negative,
            "targets": "; ".join(targets),
        })

results_df = pd.DataFrame(rows)
results_df.to_csv("sentiment_results.csv", index=False)

Every review gets a label of positive, neutral, negative or mixed, plus confidence scores. Mixed comes up a lot with restaurant reviews (“great food, rude waiter”), so don’t filter only on negative. A document that fails, because it’s too long or in an unsupported language, comes back as an error object instead of throwing. That’s why the loop checks is_error.

Find what people actually complain about

import pandas as pd

results_df = pd.read_csv("sentiment_results.csv")
print(results_df["sentiment"].value_counts())

complaints = (
    results_df["targets"].dropna()
    .str.split("; ").explode()
    .loc[lambda s: s.str.endswith(":negative")]
    .str.rsplit(":", n=1).str[0]
    .value_counts()
)
print(complaints.head(10))

The second list is the useful one. If “portion” and “spice” top it two weeks after the menu change, you have something concrete to take to the kitchen. Opinion mining isn’t perfect, though. It will sometimes split “chicken tacos” and “tacos” into separate targets, so skim the raw reviews behind your top few complaints before you act on them.

When we’d use a Foundry model instead

For new projects we mostly use a small LLM deployment with structured output. It handles sarcasm and mixed-language reviews better, you choose the categories, and it won’t hit a 2029 retirement date. The tradeoff is that you’re writing a prompt and paying per token instead of per 1,000-character text record. Here’s the same idea with the OpenAI client against a Foundry deployment (see our Terraform post for setting one up):

from typing import Literal

from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import OpenAI
from pydantic import BaseModel


class ReviewSentiment(BaseModel):
    sentiment: Literal["positive", "neutral", "negative", "mixed"]
    complaints: list[str]


client = OpenAI(
    base_url="https://<your-foundry-resource>.openai.azure.com/openai/v1/",
    api_key=get_bearer_token_provider(DefaultAzureCredential(), "https://ai.azure.com/.default"),
)

review = "Loved the new tacos, but the portion was tiny and the salsa was way too hot."
response = client.responses.parse(
    model="chat",  # your deployment name
    input=[
        {"role": "developer", "content": "Classify this restaurant review. "
         "List specific complaints as short phrases, e.g. 'small portions'."},
        {"role": "user", "content": review},
    ],
    text_format=ReviewSentiment,
)
print(response.output_parsed)

Run both on a few hundred of your own reviews before you decide, and read the ones where they disagree. That small pile tells you more about which approach fits your data than any benchmark will.

We’re GDS, a consulting team that builds AI automations and runs them in our clients’ own cloud. If that’s on your plan, here’s what we do.

Carlos Noguera

AI solutions architect, GDS. CISSP-certified architect for AI, cloud and DevOps. Leads GDS engagements from the first call through support.

What should your team stop doing by hand?

A free 20-minute AI Fit Call shows where AI helps first and what it would take.

Book a free AI Fit CallNot ready for a call? Email us