Azure AI Text Analytics Client Library for Python

5.4.0 · active · verified Tue Apr 14

The Azure AI Text Analytics client library for Python provides a robust interface for interacting with the Azure Cognitive Service for Language. This cloud-based service offers a suite of Natural Language Processing (NLP) features, including sentiment analysis, named entity recognition, language detection, key phrase extraction, and more. Currently at version 5.4.0, the library is actively maintained as part of the Azure SDK for Python, with frequent minor and patch releases to support the evolving Azure Language service APIs.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate a `TextAnalyticsClient` using an API key and endpoint, and then perform sentiment analysis on a batch of documents. Ensure you replace placeholder credentials with your actual Azure Language service endpoint and API key, preferably via environment variables.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

# Set environment variables for endpoint and key
# AZURE_LANGUAGE_ENDPOINT='https://YOUR_RESOURCE_NAME.cognitiveservices.azure.com/'
# AZURE_LANGUAGE_KEY='YOUR_API_KEY'

endpoint = os.environ.get('AZURE_LANGUAGE_ENDPOINT', 'YOUR_LANGUAGE_ENDPOINT')
key = os.environ.get('AZURE_LANGUAGE_KEY', 'YOUR_LANGUAGE_KEY')

if endpoint == 'YOUR_LANGUAGE_ENDPOINT' or key == 'YOUR_LANGUAGE_KEY':
    print("Please set the 'AZURE_LANGUAGE_ENDPOINT' and 'AZURE_LANGUAGE_KEY' environment variables.")
else:
    try:
        text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint, 
            credential=AzureKeyCredential(key)
        )

        documents = [
            "I had a wonderful trip to Seattle last week.",
            "The coffee was terrible and the staff was rude.",
            "The city was beautiful, but the weather was rainy."
        ]

        response = text_analytics_client.analyze_sentiment(documents=documents)

        for doc in response:
            if not doc.is_error:
                print(f"Document Text: {documents[doc.id]}")
                print(f"Overall Sentiment: {doc.sentiment}")
                print("Sentence sentiments:")
                for sentence in doc.sentences:
                    print(f"  Sentence: {sentence.text}")
                    print(f"  Sentiment: {sentence.sentiment}")
                    print(f"  Positive score: {round(sentence.confidence_scores.positive, 2)}")
                    print(f"  Neutral score: {round(sentence.confidence_scores.neutral, 2)}")
                    print(f"  Negative score: {round(sentence.confidence_scores.negative, 2)}\n")
            else:
                print(f"Document ID: {doc.id}, Error: {doc.error}")

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

view raw JSON →