快速入門:情感分析與意見挖掘

參考文件 | 其他範例 | 套件 (NuGet) | 程式庫原始程式碼

使用此快速入門,透過適用於 .NET 的用戶端程式庫來建立情感分析應用程式。 在下列範例中,您將建立 C# 應用程式,該應用程式可識別以文字樣本表達的情緒,並執行以外觀為基礎的情感分析。

Prerequisites

設定

建立 Azure 資源

您必須部署 Azure 資源,才能使用下列程式碼範例。 此資源將包含金鑰和端點,供您用來驗證您傳送至語言服務的 API 呼叫。

  1. 使用下列連結,以透過 Azure 入口網站建立語言資源。 您必須使用 Azure 訂用帳戶進行登入。

  2. 在所出現的 [選取其他功能] 畫面上,選取 [繼續以建立您的資源]。

    顯示 Azure 入口網站中其他功能選項的螢幕擷取畫面。

  3. 在 [建立語言] 畫面中,提供下列資訊:

    詳細資料 描述
    訂用帳戶 資源將要建立關聯的訂用帳戶。 從下拉式功能表中選取您的 Azure 訂用帳戶。
    資源群組 資源群組是一個容器,當中會儲存您所建立的資源。 選取 [新建] 來建立新的資源群組。
    區域 語言資源的位置。 區域不同可能會依據您的實體位置而造成延遲,但不會影響您資源執行階段的可用性。 在本快速入門中,請選取您鄰近的可用區域,或選擇 [美國東部]。
    名稱 語言資源的名稱。 此名稱也會用來建立端點 URL,供您的應用程式用來傳送 API 要求。
    定價層 語言資源的定價層。 您可以使用 [免費 F0] 層來試用服務,之後可升級至付費層以用於實際執行環境。

    顯示在 Azure 入口網站建立資源詳細資料的螢幕擷取畫面。

  4. 請確定已核取 [負責任 AI 通知] 核取方塊。

  5. 選取頁面底部的 [檢閱 + 建立] 。

  6. 在所出現的畫面中,確定驗證已通過,且您已輸入正確的資訊。 然後選取 [建立]。

取得金鑰和端點

接下來,您將需要來自資源的金鑰與端點,以將應用程式連線至該 API。 您稍後會在快速入門中將金鑰和端點貼到程式碼中。

  1. 成功部署語言資源後,按一下 [後續步驟] 下的 [前往資源]。

    顯示部署資源之後的後續步驟螢幕擷取畫面。

  2. 在資源的畫面上,選取左側導覽功能表上的 [金鑰和端點]。 在下列步驟中,您將使用其中一個金鑰和端點。

    顯示資源的金鑰和端點區段的螢幕擷取畫面。

建立環境變數

您的應用程式必須經過驗證後,才能傳送 API 要求。 在生產環境中,請運用安全的方式來儲存和存取您的登入資訊。 在此範例中,您會在執行應用程式的本機電腦上將認證寫入環境變數。

提示

請勿在程式碼中直接包含索引碼,且切勿公開張貼索引碼。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

若要設定語言資源金鑰的環境變數,請開啟主控台視窗,並遵循作業系統和開發環境的指示進行。

  1. 若要設定 LANGUAGE_KEY 環境變數,請將 your-key 取代為您資源的其中一個金鑰。
  2. 若要設定 LANGUAGE_ENDPOINT 環境變數,請將 your-endpoint 取代為您資源的端點。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果您只需要存取目前執行中主控台的環境變數,您可以使用 set (而不是 setx) 來設定環境變數。

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 做為編輯器,請在執行範例前重新啟動 Visual Studio。

建立新的 .NET Core 應用程式

使用 Visual Studio IDE,建立新的 .NET Core 主控台應用程式。 這會建立 "Hello World" 專案,內含單一 C# 原始程式檔:program.cs。

以滑鼠右鍵按一下 [方案總管] 中的解決方案,然後選取 [管理 NuGet 套件],以安裝用戶端程式庫。 在開啟的封裝管理員中,選取 [瀏覽] 並搜尋 Azure.AI.TextAnalytics。 選取版本 5.2.0,然後 安裝。 您也可以使用套件管理員主控台

程式碼範例

將下列程式碼複製到 program.cs 檔案中,並執行該程式碼。

using Azure;
using System;
using Azure.AI.TextAnalytics;
using System.Collections.Generic;

namespace Example
{
    class Program
    {
        // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
        static string languageKey = Environment.GetEnvironmentVariable("LANGUAGE_KEY");
        static string languageEndpoint = Environment.GetEnvironmentVariable("LANGUAGE_ENDPOINT");

        private static readonly AzureKeyCredential credentials = new AzureKeyCredential(languageKey);
        private static readonly Uri endpoint = new Uri(languageEndpoint);

        // Example method for detecting opinions text. 
        static void SentimentAnalysisWithOpinionMiningExample(TextAnalyticsClient client)
        {
            var documents = new List<string>
            {
                "The food and service were unacceptable. The concierge was nice, however."
            };

            AnalyzeSentimentResultCollection reviews = client.AnalyzeSentimentBatch(documents, options: new AnalyzeSentimentOptions()
            {
                IncludeOpinionMining = true
            });

            foreach (AnalyzeSentimentResult review in reviews)
            {
                Console.WriteLine($"Document sentiment: {review.DocumentSentiment.Sentiment}\n");
                Console.WriteLine($"\tPositive score: {review.DocumentSentiment.ConfidenceScores.Positive:0.00}");
                Console.WriteLine($"\tNegative score: {review.DocumentSentiment.ConfidenceScores.Negative:0.00}");
                Console.WriteLine($"\tNeutral score: {review.DocumentSentiment.ConfidenceScores.Neutral:0.00}\n");
                foreach (SentenceSentiment sentence in review.DocumentSentiment.Sentences)
                {
                    Console.WriteLine($"\tText: \"{sentence.Text}\"");
                    Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
                    Console.WriteLine($"\tSentence positive score: {sentence.ConfidenceScores.Positive:0.00}");
                    Console.WriteLine($"\tSentence negative score: {sentence.ConfidenceScores.Negative:0.00}");
                    Console.WriteLine($"\tSentence neutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");

                    foreach (SentenceOpinion sentenceOpinion in sentence.Opinions)
                    {
                        Console.WriteLine($"\tTarget: {sentenceOpinion.Target.Text}, Value: {sentenceOpinion.Target.Sentiment}");
                        Console.WriteLine($"\tTarget positive score: {sentenceOpinion.Target.ConfidenceScores.Positive:0.00}");
                        Console.WriteLine($"\tTarget negative score: {sentenceOpinion.Target.ConfidenceScores.Negative:0.00}");
                        foreach (AssessmentSentiment assessment in sentenceOpinion.Assessments)
                        {
                            Console.WriteLine($"\t\tRelated Assessment: {assessment.Text}, Value: {assessment.Sentiment}");
                            Console.WriteLine($"\t\tRelated Assessment positive score: {assessment.ConfidenceScores.Positive:0.00}");
                            Console.WriteLine($"\t\tRelated Assessment negative score: {assessment.ConfidenceScores.Negative:0.00}");
                        }
                    }
                }
                Console.WriteLine($"\n");
            }
        }

        static void Main(string[] args)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            SentimentAnalysisWithOpinionMiningExample(client);

            Console.Write("Press any key to exit.");
            Console.ReadKey();
        }

    }
}

輸出

Document sentiment: Mixed

    Positive score: 0.47
    Negative score: 0.52
    Neutral score: 0.00

    Text: "The food and service were unacceptable. "
    Sentence sentiment: Negative
    Sentence positive score: 0.00
    Sentence negative score: 0.99
    Sentence neutral score: 0.00

    Target: food, Value: Negative
    Target positive score: 0.00
    Target negative score: 1.00
            Related Assessment: unacceptable, Value: Negative
            Related Assessment positive score: 0.00
            Related Assessment negative score: 1.00
    Target: service, Value: Negative
    Target positive score: 0.00
    Target negative score: 1.00
            Related Assessment: unacceptable, Value: Negative
            Related Assessment positive score: 0.00
            Related Assessment negative score: 1.00
    Text: "The concierge was nice, however."
    Sentence sentiment: Positive
    Sentence positive score: 0.94
    Sentence negative score: 0.05
    Sentence neutral score: 0.01

    Target: concierge, Value: Positive
    Target positive score: 1.00
    Target negative score: 0.00
            Related Assessment: nice, Value: Positive
            Related Assessment positive score: 1.00
            Related Assessment negative score: 0.00

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除其關聯的任何其他資源。

使用下列命令來刪除您針對此快速入門建立的環境變數。

reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f

後續步驟

參考文件 | 其他範例 | 套件 (Maven) | 程式庫原始程式碼

使用此快速入門,透過適用於 Java 的用戶端程式庫來建立情感分析應用程式。 在下列範例中,您將建立 Java 應用程式,該應用程式可識別以文字樣本表達的情緒,並執行以外觀為基礎的情感分析。

Prerequisites

設定

建立 Azure 資源

您必須部署 Azure 資源,才能使用下列程式碼範例。 此資源將包含金鑰和端點,供您用來驗證您傳送至語言服務的 API 呼叫。

  1. 使用下列連結,以透過 Azure 入口網站建立語言資源。 您必須使用 Azure 訂用帳戶進行登入。

  2. 在所出現的 [選取其他功能] 畫面上,選取 [繼續以建立您的資源]。

    顯示 Azure 入口網站中其他功能選項的螢幕擷取畫面。

  3. 在 [建立語言] 畫面中,提供下列資訊:

    詳細資料 描述
    訂用帳戶 資源將要建立關聯的訂用帳戶。 從下拉式功能表中選取您的 Azure 訂用帳戶。
    資源群組 資源群組是一個容器,當中會儲存您所建立的資源。 選取 [新建] 來建立新的資源群組。
    區域 語言資源的位置。 區域不同可能會依據您的實體位置而造成延遲,但不會影響您資源執行階段的可用性。 在本快速入門中,請選取您鄰近的可用區域,或選擇 [美國東部]。
    名稱 語言資源的名稱。 此名稱也會用來建立端點 URL,供您的應用程式用來傳送 API 要求。
    定價層 語言資源的定價層。 您可以使用 [免費 F0] 層來試用服務,之後可升級至付費層以用於實際執行環境。

    顯示在 Azure 入口網站建立資源詳細資料的螢幕擷取畫面。

  4. 請確定已核取 [負責任 AI 通知] 核取方塊。

  5. 選取頁面底部的 [檢閱 + 建立] 。

  6. 在所出現的畫面中,確定驗證已通過,且您已輸入正確的資訊。 然後選取 [建立]。

取得金鑰和端點

接下來,您將需要來自資源的金鑰與端點,以將應用程式連線至該 API。 您稍後會在快速入門中將金鑰和端點貼到程式碼中。

  1. 成功部署語言資源後,按一下 [後續步驟] 下的 [前往資源]。

    顯示部署資源之後的後續步驟螢幕擷取畫面。

  2. 在資源的畫面上,選取左側導覽功能表上的 [金鑰和端點]。 在下列步驟中,您將使用其中一個金鑰和端點。

    顯示資源的金鑰和端點區段的螢幕擷取畫面。

建立環境變數

您的應用程式必須經過驗證後,才能傳送 API 要求。 在生產環境中,請運用安全的方式來儲存和存取您的登入資訊。 在此範例中,您會在執行應用程式的本機電腦上將認證寫入環境變數。

提示

請勿在程式碼中直接包含索引碼,且切勿公開張貼索引碼。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

若要設定語言資源金鑰的環境變數,請開啟主控台視窗,並遵循作業系統和開發環境的指示進行。

  1. 若要設定 LANGUAGE_KEY 環境變數,請將 your-key 取代為您資源的其中一個金鑰。
  2. 若要設定 LANGUAGE_ENDPOINT 環境變數,請將 your-endpoint 取代為您資源的端點。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果您只需要存取目前執行中主控台的環境變數,您可以使用 set (而不是 setx) 來設定環境變數。

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 做為編輯器,請在執行範例前重新啟動 Visual Studio。

新增用戶端程式庫

在您慣用的 IDE 或開發環境中建立 Maven 專案。 然後,在專案的 pom.xml 檔案中新增下列相依性。 您可以在線上找到其他建置工具的實作語法。

<dependencies>
     <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-textanalytics</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

程式碼範例

建立名為 Example.java 的 Java 檔案。 開啟檔案並複製下列程式碼。 然後執行程式碼。

import com.azure.core.credential.AzureKeyCredential;
import com.azure.ai.textanalytics.models.*;
import com.azure.ai.textanalytics.TextAnalyticsClientBuilder;
import com.azure.ai.textanalytics.TextAnalyticsClient;

public class Example {
    
    // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
    private static String languageKey = System.getenv("LANGUAGE_KEY");
    private static String languageEndpoint = System.getenv("LANGUAGE_ENDPOINT");

    public static void main(String[] args) {
        TextAnalyticsClient client = authenticateClient(languageKey, languageEndpoint);
        sentimentAnalysisWithOpinionMiningExample(client);
    }
    // Method to authenticate the client object with your key and endpoint.
    static TextAnalyticsClient authenticateClient(String key, String endpoint) {
        return new TextAnalyticsClientBuilder()
                .credential(new AzureKeyCredential(key))
                .endpoint(endpoint)
                .buildClient();
    }
    // Example method for detecting sentiment and opinions in text.
    static void sentimentAnalysisWithOpinionMiningExample(TextAnalyticsClient client)
    {
        // The document that needs be analyzed.
        String document = "The food and service were unacceptable. The concierge was nice, however.";

        System.out.printf("Document = %s%n", document);

        AnalyzeSentimentOptions options = new AnalyzeSentimentOptions().setIncludeOpinionMining(true);
        final DocumentSentiment documentSentiment = client.analyzeSentiment(document, "en", options);
        SentimentConfidenceScores scores = documentSentiment.getConfidenceScores();
        System.out.printf(
                "Recognized document sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n",
                documentSentiment.getSentiment(), scores.getPositive(), scores.getNeutral(), scores.getNegative());


        documentSentiment.getSentences().forEach(sentenceSentiment -> {
            SentimentConfidenceScores sentenceScores = sentenceSentiment.getConfidenceScores();
            System.out.printf("\tSentence sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n",
                    sentenceSentiment.getSentiment(), sentenceScores.getPositive(), sentenceScores.getNeutral(), sentenceScores.getNegative());
            sentenceSentiment.getOpinions().forEach(opinion -> {
                TargetSentiment targetSentiment = opinion.getTarget();
                System.out.printf("\t\tTarget sentiment: %s, target text: %s%n", targetSentiment.getSentiment(),
                        targetSentiment.getText());
                for (AssessmentSentiment assessmentSentiment : opinion.getAssessments()) {
                    System.out.printf("\t\t\t'%s' assessment sentiment because of \"%s\". Is the assessment negated: %s.%n",
                            assessmentSentiment.getSentiment(), assessmentSentiment.getText(), assessmentSentiment.isNegated());
                }
            });
        });
    }
}

輸出

Document = The food and service were unacceptable. The concierge was nice, however.
Recognized document sentiment: mixed, positive score: 0.470000, neutral score: 0.000000, negative score: 0.520000.
	Sentence sentiment: negative, positive score: 0.000000, neutral score: 0.000000, negative score: 0.990000.
		Target sentiment: negative, target text: food
			'negative' assessment sentiment because of "unacceptable". Is the assessment negated: false.
		Target sentiment: negative, target text: service
			'negative' assessment sentiment because of "unacceptable". Is the assessment negated: false.
	Sentence sentiment: positive, positive score: 0.940000, neutral score: 0.010000, negative score: 0.050000.
		Target sentiment: positive, target text: concierge
			'positive' assessment sentiment because of "nice". Is the assessment negated: false.

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除其關聯的任何其他資源。

使用下列命令來刪除您針對此快速入門建立的環境變數。

reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f

後續步驟

參考文件 | 其他範例 | 套件 (npm) | 程式庫原始程式碼

使用此快速入門,透過適用於 Node.js 的用戶端程式庫來建立情感分析應用程式。 在下列範例中,您將建立 JavaScript 應用程式,該應用程式可識別以文字樣本表達的情緒,並執行以外觀為基礎的情感分析。

Prerequisites

設定

建立 Azure 資源

您必須部署 Azure 資源,才能使用下列程式碼範例。 此資源將包含金鑰和端點,供您用來驗證您傳送至語言服務的 API 呼叫。

  1. 使用下列連結,以透過 Azure 入口網站建立語言資源。 您必須使用 Azure 訂用帳戶進行登入。

  2. 在所出現的 [選取其他功能] 畫面上,選取 [繼續以建立您的資源]。

    顯示 Azure 入口網站中其他功能選項的螢幕擷取畫面。

  3. 在 [建立語言] 畫面中,提供下列資訊:

    詳細資料 描述
    訂用帳戶 資源將要建立關聯的訂用帳戶。 從下拉式功能表中選取您的 Azure 訂用帳戶。
    資源群組 資源群組是一個容器,當中會儲存您所建立的資源。 選取 [新建] 來建立新的資源群組。
    區域 語言資源的位置。 區域不同可能會依據您的實體位置而造成延遲,但不會影響您資源執行階段的可用性。 在本快速入門中,請選取您鄰近的可用區域,或選擇 [美國東部]。
    名稱 語言資源的名稱。 此名稱也會用來建立端點 URL,供您的應用程式用來傳送 API 要求。
    定價層 語言資源的定價層。 您可以使用 [免費 F0] 層來試用服務,之後可升級至付費層以用於實際執行環境。

    顯示在 Azure 入口網站建立資源詳細資料的螢幕擷取畫面。

  4. 請確定已核取 [負責任 AI 通知] 核取方塊。

  5. 選取頁面底部的 [檢閱 + 建立] 。

  6. 在所出現的畫面中,確定驗證已通過,且您已輸入正確的資訊。 然後選取 [建立]。

取得金鑰和端點

接下來,您將需要來自資源的金鑰與端點,以將應用程式連線至該 API。 您稍後會在快速入門中將金鑰和端點貼到程式碼中。

  1. 成功部署語言資源後,按一下 [後續步驟] 下的 [前往資源]。

    顯示部署資源之後的後續步驟螢幕擷取畫面。

  2. 在資源的畫面上,選取左側導覽功能表上的 [金鑰和端點]。 在下列步驟中,您將使用其中一個金鑰和端點。

    顯示資源的金鑰和端點區段的螢幕擷取畫面。

建立環境變數

您的應用程式必須經過驗證後,才能傳送 API 要求。 在生產環境中,請運用安全的方式來儲存和存取您的登入資訊。 在此範例中,您會在執行應用程式的本機電腦上將認證寫入環境變數。

提示

請勿在程式碼中直接包含索引碼,且切勿公開張貼索引碼。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

若要設定語言資源金鑰的環境變數,請開啟主控台視窗,並遵循作業系統和開發環境的指示進行。

  1. 若要設定 LANGUAGE_KEY 環境變數,請將 your-key 取代為您資源的其中一個金鑰。
  2. 若要設定 LANGUAGE_ENDPOINT 環境變數,請將 your-endpoint 取代為您資源的端點。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果您只需要存取目前執行中主控台的環境變數,您可以使用 set (而不是 setx) 來設定環境變數。

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 做為編輯器,請在執行範例前重新啟動 Visual Studio。

建立新的 Node.js 應用程式

在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為您的應用程式建立新的目錄,並瀏覽至該目錄。

mkdir myapp 

cd myapp

執行命令 npm init,以使用 package.json 檔案建立節點應用程式。

npm init

安裝用戶端程式庫

安裝 npm 套件:

npm install @azure/ai-language-text

程式碼範例

開啟檔案並複製下列程式碼。 然後執行程式碼。

"use strict";

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

// This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
const key = process.env.LANGUAGE_KEY;
const endpoint = process.env.LANGUAGE_ENDPOINT;


//an example document for sentiment analysis and opinion mining
const documents = [{
    text: "The food and service were unacceptable. The concierge was nice, however.",
    id: "0",
    language: "en"
  }];
  
async function main() {
  console.log("=== Sentiment analysis and opinion mining sample ===");

  const client = new TextAnalysisClient(endpoint, new AzureKeyCredential(key));

  const results = await client.analyze("SentimentAnalysis", documents, {
    includeOpinionMining: true,
  });

  for (let i = 0; i < results.length; i++) {
    const result = results[i];
    console.log(`- Document ${result.id}`);
    if (!result.error) {
      console.log(`\tDocument text: ${documents[i].text}`);
      console.log(`\tOverall Sentiment: ${result.sentiment}`);
      console.log("\tSentiment confidence scores:", result.confidenceScores);
      console.log("\tSentences");
      for (const { sentiment, confidenceScores, opinions } of result.sentences) {
        console.log(`\t- Sentence sentiment: ${sentiment}`);
        console.log("\t  Confidence scores:", confidenceScores);
        console.log("\t  Mined opinions");
        for (const { target, assessments } of opinions) {
          console.log(`\t\t- Target text: ${target.text}`);
          console.log(`\t\t  Target sentiment: ${target.sentiment}`);
          console.log("\t\t  Target confidence scores:", target.confidenceScores);
          console.log("\t\t  Target assessments");
          for (const { text, sentiment } of assessments) {
            console.log(`\t\t\t- Text: ${text}`);
            console.log(`\t\t\t  Sentiment: ${sentiment}`);
          }
        }
      }
    } else {
      console.error(`\tError: ${result.error}`);
    }
  }
}
  
main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

輸出

=== Sentiment analysis and opinion mining sample ===
- Document 0
    Document text: The food and service were unacceptable. The concierge was nice, however.
    Overall Sentiment: mixed
    Sentiment confidence scores: { positive: 0.49, neutral: 0, negative: 0.5 }
    Sentences
    - Sentence sentiment: negative
      Confidence scores: { positive: 0, neutral: 0, negative: 1 }
      Mined opinions
            - Target text: food
              Target sentiment: negative
              Target confidence scores: { positive: 0.01, negative: 0.99 }
              Target assessments
                    - Text: unacceptable
                      Sentiment: negative
            - Target text: service
              Target sentiment: negative
              Target confidence scores: { positive: 0.01, negative: 0.99 }
              Target assessments
                    - Text: unacceptable
                      Sentiment: negative
    - Sentence sentiment: positive
      Confidence scores: { positive: 0.98, neutral: 0.01, negative: 0.01 }
      Mined opinions
            - Target text: concierge
              Target sentiment: positive
              Target confidence scores: { positive: 1, negative: 0 }
              Target assessments
                    - Text: nice
                      Sentiment: positive

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除其關聯的任何其他資源。

使用下列命令來刪除您針對此快速入門建立的環境變數。

reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f

後續步驟

參考文件 | 其他範例 | 套件 (PyPi) | 程式庫原始程式碼

使用此快速入門,透過適用於 Python 的用戶端程式庫來建立情感分析應用程式。 在下列範例中,您將建立 Python 應用程式,該應用程式可識別以文字樣本表達的情緒,並執行以外觀為基礎的情感分析。

Prerequisites

設定

建立 Azure 資源

您必須部署 Azure 資源,才能使用下列程式碼範例。 此資源將包含金鑰和端點,供您用來驗證您傳送至語言服務的 API 呼叫。

  1. 使用下列連結,以透過 Azure 入口網站建立語言資源。 您必須使用 Azure 訂用帳戶進行登入。

  2. 在所出現的 [選取其他功能] 畫面上,選取 [繼續以建立您的資源]。

    顯示 Azure 入口網站中其他功能選項的螢幕擷取畫面。

  3. 在 [建立語言] 畫面中,提供下列資訊:

    詳細資料 描述
    訂用帳戶 資源將要建立關聯的訂用帳戶。 從下拉式功能表中選取您的 Azure 訂用帳戶。
    資源群組 資源群組是一個容器,當中會儲存您所建立的資源。 選取 [新建] 來建立新的資源群組。
    區域 語言資源的位置。 區域不同可能會依據您的實體位置而造成延遲,但不會影響您資源執行階段的可用性。 在本快速入門中,請選取您鄰近的可用區域,或選擇 [美國東部]。
    名稱 語言資源的名稱。 此名稱也會用來建立端點 URL,供您的應用程式用來傳送 API 要求。
    定價層 語言資源的定價層。 您可以使用 [免費 F0] 層來試用服務,之後可升級至付費層以用於實際執行環境。

    顯示在 Azure 入口網站建立資源詳細資料的螢幕擷取畫面。

  4. 請確定已核取 [負責任 AI 通知] 核取方塊。

  5. 選取頁面底部的 [檢閱 + 建立] 。

  6. 在所出現的畫面中,確定驗證已通過,且您已輸入正確的資訊。 然後選取 [建立]。

取得金鑰和端點

接下來,您將需要來自資源的金鑰與端點,以將應用程式連線至該 API。 您稍後會在快速入門中將金鑰和端點貼到程式碼中。

  1. 成功部署語言資源後,按一下 [後續步驟] 下的 [前往資源]。

    顯示部署資源之後的後續步驟螢幕擷取畫面。

  2. 在資源的畫面上,選取左側導覽功能表上的 [金鑰和端點]。 在下列步驟中,您將使用其中一個金鑰和端點。

    顯示資源的金鑰和端點區段的螢幕擷取畫面。

建立環境變數

您的應用程式必須經過驗證後,才能傳送 API 要求。 在生產環境中,請運用安全的方式來儲存和存取您的登入資訊。 在此範例中,您會在執行應用程式的本機電腦上將認證寫入環境變數。

提示

請勿在程式碼中直接包含索引碼,且切勿公開張貼索引碼。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

若要設定語言資源金鑰的環境變數,請開啟主控台視窗,並遵循作業系統和開發環境的指示進行。

  1. 若要設定 LANGUAGE_KEY 環境變數,請將 your-key 取代為您資源的其中一個金鑰。
  2. 若要設定 LANGUAGE_ENDPOINT 環境變數,請將 your-endpoint 取代為您資源的端點。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果您只需要存取目前執行中主控台的環境變數,您可以使用 set (而不是 setx) 來設定環境變數。

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 做為編輯器,請在執行範例前重新啟動 Visual Studio。

安裝用戶端程式庫

安裝 Python 之後,您可以透過以下項目安裝用戶端程式庫:

pip install azure-ai-textanalytics==5.2.0

程式碼範例

建立新的 Python 檔案並複製下列程式碼。 然後執行程式碼

# This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
language_key = os.environ.get('LANGUAGE_KEY')
language_endpoint = os.environ.get('LANGUAGE_ENDPOINT')

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

# Authenticate the client using your key and endpoint 
def authenticate_client():
    ta_credential = AzureKeyCredential(language_key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=language_endpoint, 
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

# Example method for detecting sentiment and opinions in text 
def sentiment_analysis_with_opinion_mining_example(client):

    documents = [
        "The food and service were unacceptable. The concierge was nice, however."
    ]

    result = client.analyze_sentiment(documents, show_opinion_mining=True)
    doc_result = [doc for doc in result if not doc.is_error]

    positive_reviews = [doc for doc in doc_result if doc.sentiment == "positive"]
    negative_reviews = [doc for doc in doc_result if doc.sentiment == "negative"]

    positive_mined_opinions = []
    mixed_mined_opinions = []
    negative_mined_opinions = []

    for document in doc_result:
        print("Document Sentiment: {}".format(document.sentiment))
        print("Overall scores: positive={0:.2f}; neutral={1:.2f}; negative={2:.2f} \n".format(
            document.confidence_scores.positive,
            document.confidence_scores.neutral,
            document.confidence_scores.negative,
        ))
        for sentence in document.sentences:
            print("Sentence: {}".format(sentence.text))
            print("Sentence sentiment: {}".format(sentence.sentiment))
            print("Sentence score:\nPositive={0:.2f}\nNeutral={1:.2f}\nNegative={2:.2f}\n".format(
                sentence.confidence_scores.positive,
                sentence.confidence_scores.neutral,
                sentence.confidence_scores.negative,
            ))
            for mined_opinion in sentence.mined_opinions:
                target = mined_opinion.target
                print("......'{}' target '{}'".format(target.sentiment, target.text))
                print("......Target score:\n......Positive={0:.2f}\n......Negative={1:.2f}\n".format(
                    target.confidence_scores.positive,
                    target.confidence_scores.negative,
                ))
                for assessment in mined_opinion.assessments:
                    print("......'{}' assessment '{}'".format(assessment.sentiment, assessment.text))
                    print("......Assessment score:\n......Positive={0:.2f}\n......Negative={1:.2f}\n".format(
                        assessment.confidence_scores.positive,
                        assessment.confidence_scores.negative,
                    ))
            print("\n")
        print("\n")
          
sentiment_analysis_with_opinion_mining_example(client)

輸出

Document Sentiment: mixed
Overall scores: positive=0.47; neutral=0.00; negative=0.52

Sentence: The food and service were unacceptable.
Sentence sentiment: negative
Sentence score:
Positive=0.00
Neutral=0.00
Negative=0.99

......'negative' target 'food'
......Target score:
......Positive=0.00
......Negative=1.00

......'negative' assessment 'unacceptable'
......Assessment score:
......Positive=0.00
......Negative=1.00

......'negative' target 'service'
......Target score:
......Positive=0.00
......Negative=1.00

......'negative' assessment 'unacceptable'
......Assessment score:
......Positive=0.00
......Negative=1.00



Sentence: The concierge was nice, however.
Sentence sentiment: positive
Sentence score:
Positive=0.94
Neutral=0.01
Negative=0.05

......'positive' target 'concierge'
......Target score:
......Positive=1.00
......Negative=0.00

......'positive' assessment 'nice'
......Assessment score:
......Positive=1.00
......Negative=0.00

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除其關聯的任何其他資源。

使用下列命令來刪除您針對此快速入門建立的環境變數。

reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f

後續步驟

參考文件

使用本快速入門,使用 REST API 傳送情感分析要求。 在下列範例中,您將使用 cURL 來識別以文字樣本表達的情緒,並執行以外觀為基礎的情感分析。

必要條件

設定

建立 Azure 資源

您必須部署 Azure 資源,才能使用下列程式碼範例。 此資源將包含金鑰和端點,供您用來驗證您傳送至語言服務的 API 呼叫。

  1. 使用下列連結,以透過 Azure 入口網站建立語言資源。 您必須使用 Azure 訂用帳戶進行登入。

  2. 在所出現的 [選取其他功能] 畫面上,選取 [繼續以建立您的資源]。

    顯示 Azure 入口網站中其他功能選項的螢幕擷取畫面。

  3. 在 [建立語言] 畫面中,提供下列資訊:

    詳細資料 描述
    訂用帳戶 資源將要建立關聯的訂用帳戶。 從下拉式功能表中選取您的 Azure 訂用帳戶。
    資源群組 資源群組是一個容器,當中會儲存您所建立的資源。 選取 [新建] 來建立新的資源群組。
    區域 語言資源的位置。 區域不同可能會依據您的實體位置而造成延遲,但不會影響您資源執行階段的可用性。 在本快速入門中,請選取您鄰近的可用區域,或選擇 [美國東部]。
    名稱 語言資源的名稱。 此名稱也會用來建立端點 URL,供您的應用程式用來傳送 API 要求。
    定價層 語言資源的定價層。 您可以使用 [免費 F0] 層來試用服務,之後可升級至付費層以用於實際執行環境。

    顯示在 Azure 入口網站建立資源詳細資料的螢幕擷取畫面。

  4. 請確定已核取 [負責任 AI 通知] 核取方塊。

  5. 選取頁面底部的 [檢閱 + 建立] 。

  6. 在所出現的畫面中,確定驗證已通過,且您已輸入正確的資訊。 然後選取 [建立]。

取得金鑰和端點

接下來,您將需要來自資源的金鑰與端點,以將應用程式連線至該 API。 您稍後會在快速入門中將金鑰和端點貼到程式碼中。

  1. 成功部署語言資源後,按一下 [後續步驟] 下的 [前往資源]。

    顯示部署資源之後的後續步驟螢幕擷取畫面。

  2. 在資源的畫面上,選取左側導覽功能表上的 [金鑰和端點]。 在下列步驟中,您將使用其中一個金鑰和端點。

    顯示資源的金鑰和端點區段的螢幕擷取畫面。

建立環境變數

您的應用程式必須經過驗證後,才能傳送 API 要求。 在生產環境中,請運用安全的方式來儲存和存取您的登入資訊。 在此範例中,您會在執行應用程式的本機電腦上將認證寫入環境變數。

提示

請勿在程式碼中直接包含索引碼,且切勿公開張貼索引碼。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

若要設定語言資源金鑰的環境變數,請開啟主控台視窗,並遵循作業系統和開發環境的指示進行。

  1. 若要設定 LANGUAGE_KEY 環境變數,請將 your-key 取代為您資源的其中一個金鑰。
  2. 若要設定 LANGUAGE_ENDPOINT 環境變數,請將 your-endpoint 取代為您資源的端點。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果您只需要存取目前執行中主控台的環境變數,您可以使用 set (而不是 setx) 來設定環境變數。

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 做為編輯器,請在執行範例前重新啟動 Visual Studio。

使用範例要求本文來建立 JSON 檔案

在程式碼編輯器中,建立名為 test_sentiment_payload.json 的新檔案,並複製下列 JSON 範例。 在下一個步驟中,會將此範例要求傳送至 API。

{
	"kind": "SentimentAnalysis",
	"parameters": {
		"modelVersion": "latest",
		"opinionMining": "True"
	},
	"analysisInput":{
		"documents":[
			{
				"id":"1",
				"language":"en",
				"text": "The food and service were unacceptable. The concierge was nice, however."
			}
		]
	}
} 

test_sentiment_payload.json 儲存在電腦上的某個位置。 例如,您的桌面。

傳送情感分析和意見挖掘 API 要求

注意

下列範例包含對情感分析意見挖掘功能的要求,此參數提供有關與文字中目標 (名詞) 相關評量 (形容詞) 的詳細資訊。

使用下列命令,透過您正在使用的程式來傳送 API 要求。 將命令複製到終端機,然後執行該命令。

參數 (parameter) 描述
-X POST <endpoint> 指定用於存取 API 的端點。
-H Content-Type: application/json 用於傳送 JSON 資料的內容類型。
-H "Ocp-Apim-Subscription-Key:<key> 指定用於存取 API 的金鑰。
-d <documents> JSON 檔案,其中包含您想要傳送的文件。

C:\Users\<myaccount>\Desktop\test_sentiment_payload.json 取代為您在上一個步驟中所建立範例 JSON 要求檔案的位置。

命令提示字元

curl -X POST "%LANGUAGE_ENDPOINT%/language/:analyze-text?api-version=2023-04-15-preview" ^
-H "Content-Type: application/json" ^
-H "Ocp-Apim-Subscription-Key: %LANGUAGE_KEY%" ^
-d "@C:\Users\<myaccount>\Desktop\test_sentiment_payload.json"

PowerShell

curl.exe -X POST $env:LANGUAGE_ENDPOINT/language/:analyze-text?api-version=2023-04-15-preview `
-H "Content-Type: application/json" `
-H "Ocp-Apim-Subscription-Key: $env:LANGUAGE_KEY" `
-d "@C:\Users\<myaccount>\Desktop\test_sentiment_payload.json"

JSON 回應

{
	"kind": "SentimentAnalysisResults",
	"results": {
		"documents": [{
			"id": "1",
			"sentiment": "mixed",
			"confidenceScores": {
				"positive": 0.47,
				"neutral": 0.0,
				"negative": 0.52
			},
			"sentences": [{
				"sentiment": "negative",
				"confidenceScores": {
					"positive": 0.0,
					"neutral": 0.0,
					"negative": 0.99
				},
				"offset": 0,
				"length": 40,
				"text": "The food and service were unacceptable. ",
				"targets": [{
					"sentiment": "negative",
					"confidenceScores": {
						"positive": 0.0,
						"negative": 1.0
					},
					"offset": 4,
					"length": 4,
					"text": "food",
					"relations": [{
						"relationType": "assessment",
						"ref": "#/documents/0/sentences/0/assessments/0"
					}]
				}, {
					"sentiment": "negative",
					"confidenceScores": {
						"positive": 0.0,
						"negative": 1.0
					},
					"offset": 13,
					"length": 7,
					"text": "service",
					"relations": [{
						"relationType": "assessment",
						"ref": "#/documents/0/sentences/0/assessments/0"
					}]
				}],
				"assessments": [{
					"sentiment": "negative",
					"confidenceScores": {
						"positive": 0.0,
						"negative": 1.0
					},
					"offset": 26,
					"length": 12,
					"text": "unacceptable",
					"isNegated": false
				}]
			}, {
				"sentiment": "positive",
				"confidenceScores": {
					"positive": 0.94,
					"neutral": 0.01,
					"negative": 0.05
				},
				"offset": 40,
				"length": 32,
				"text": "The concierge was nice, however.",
				"targets": [{
					"sentiment": "positive",
					"confidenceScores": {
						"positive": 1.0,
						"negative": 0.0
					},
					"offset": 44,
					"length": 9,
					"text": "concierge",
					"relations": [{
						"relationType": "assessment",
						"ref": "#/documents/0/sentences/1/assessments/0"
					}]
				}],
				"assessments": [{
					"sentiment": "positive",
					"confidenceScores": {
						"positive": 1.0,
						"negative": 0.0
					},
					"offset": 58,
					"length": 4,
					"text": "nice",
					"isNegated": false
				}]
			}],
			"warnings": []
		}],
		"errors": [],
		"modelVersion": "2022-06-01"
	}
}

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除其關聯的任何其他資源。

使用下列命令來刪除您針對此快速入門建立的環境變數。

reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f

後續步驟