Natural Language Processing with Azure Text Analytics

Introduction

Natural Language Processing (NLP) is essential for extracting meaningful insights from text data. Whether analyzing customer feedback, processing documents, or detecting sentiments in user reviews, NLP enables smarter decision-making.

Azure Text Analytics provides a powerful cloud-based API for NLP tasks, eliminating the need to build and train machine learning models from scratch. With just an API request, you can:

  • ✅ Extract key phrases from text
  • ✅ Detect language automatically
  • ✅ Perform sentiment analysis

This article walks through setting up Azure Text Analytics, sending text data for processing, and visualizing the results.

Language Service

1️⃣ Setting Up Azure Text Analytics

Before making API calls, an Azure Text Analytics resource needs to be set up.

Steps to Create a Text Analytics Resource

  1. Log in to Azure Portal.
  2. Click Create a resource → Search for "Text Analytics".
  3. Select Cognitive Services → Text Analytics.
  4. Fill in the required details:
    • Subscription: Choose an active Azure subscription.
    • Resource Group: Create or use an existing one.
    • Region: Pick the nearest Azure region.
    • Pricing Tier: Start with the free F0 tier (if available).
  5. Click Review + Create → then Create.

Once the deployment completes, go to "Keys and Endpoint" in the Text Analytics resource to get:

  • ✔ API Key
  • ✔ Endpoint URL
    Create language

2️⃣ Sending Text Data to Azure Text Analytics API

With the API Key and Endpoint ready, it's time to send text data for NLP processing.

Here’s a Python script to extract key phrases, detect language, and analyze sentiment:

Python Script

This dataset consists of three sample texts in different languages. Each document is assigned an ID, a language code, and the text to be analyzed.

3️⃣ Extracting Key Phrases

Key phrase extraction helps identify the most relevant words from a block of text. This feature is useful for:

  • Summarizing text in a document.

  • Extracting key topics from customer reviews.

  • Identifying frequently mentioned terms in a dataset.

API Call for Key Phrases

To extract key phrases, send a POST request to the API

response = requests.post(f"{ENDPOINT}/keyPhrases", headers=headers, json=documents)

result = response.json()

print("Key Phrases Extraction Results:")

for doc in result["documents"]:
    print(f"Document {doc['id']}: {doc['keyPhrases']}")

📌 Example Output

Key Phrases Extraction Results:

Document 1: ['Azure Text Analytics', 'NLP']

Document 2: ['travailler', 'Azure AI']

Document 3: ['inteligencia artificial', 'Azure']

4️⃣ Detecting Language

For multilingual text, Azure’s Language Detection API automatically detects the language and confidence score.

API Call for Language Detection

response = requests.post(f"{ENDPOINT}/languages", headers=headers, json=documents)

result = response.json()

print("Language Detection Results:")

for doc in result["documents"]:
    print(f"Document {doc['id']}: {doc['detectedLanguage']['name']} "
          f"(Confidence: {doc['detectedLanguage']['confidenceScore']:.2f})")

📌 Example Output

Language Detection Results:

Document 1: English (Confidence: 0.99)

Document 2: French (Confidence: 0.97)

Document 3: Spanish (Confidence: 0.98)

5️⃣ Performing Sentiment Analysis

Sentiment Analysis determines whether a sentence is positive, negative, or neutral.

API Call for Sentiment Analysis

response = requests.post(f"{ENDPOINT}/sentiment", headers=headers, json=documents)

result = response.json()

print("Sentiment Analysis Results:")

for doc in result["documents"]:
    print(f"Document {doc['id']}: Sentiment - {doc['sentiment']} (Confidence: {doc['confidenceScores']})")

📌 Example Output

Sentiment Analysis Results:

Document 1: Sentiment - positive (Confidence: {'positive': 0.98, 'neutral': 0.01, 'negative': 0.01})

Document 2: Sentiment - positive (Confidence: {'positive': 0.95, 'neutral': 0.04, 'negative': 0.01})

Document 3: Sentiment - neutral (Confidence: {'positive': 0.33, 'neutral': 0.62, 'negative': 0.05})

6️⃣ Visualizing NLP Results

To better interpret sentiment scores, results can be plotted using Matplotlib:

import matplotlib.pyplot as plt

labels = ["Positive", "Neutral", "Negative"]
scores = [0.98, 0.01, 0.01]  # Replace with actual confidence scores

plt.bar(labels, scores, color=["green", "gray", "red"])
plt.xlabel("Sentiment")
plt.ylabel("Confidence Score")
plt.title("Sentiment Analysis Results")
plt.show()

🚀 Conclusion

Azure Text Analytics simplifies Natural Language Processing by providing pre-built NLP models for key phrase extraction, language detection, and sentiment analysis.

🔗 Further Learning

Up Next
    Ebook Download
    View all
    Learn
    View all