快速入门:情绪分析和观点挖掘

参考文档 | 其他示例 | 包 (NuGet) | 库源代码

借助本快速入门,使用 .NET 客户端库创建情绪分析应用程序。 在以下示例中,你将创建一个 C# 应用程序,该应用程序可以识别文本示例中表达的情绪,并执行基于方面的情绪分析。

先决条件

设置

创建 Azure 资源

若要使用下面的代码示例,需要部署 Azure 资源。 此资源将包含一个密钥和终结点,用于对发送到语言服务的 API 调用进行身份验证。

  1. 使用以下链接通过 Azure 门户创建语言资源。 需要使用 Azure 订阅登录。

  2. 在显示的“选择其他功能”屏幕上,选择“继续创建资源”。

    A screenshot showing additional feature options in the Azure portal.

  3. 在“创建语言”屏幕中,提供以下信息:

    详细信息 说明
    订阅 资源将与之关联的订阅帐户。 从下拉菜单选择 Azure 订阅。
    资源组 资源组是存储所创建资源的容器。 选择“新建”来创建一个新的资源组。
    区域 语言资源的位置。 不同区域可能会导致延迟,具体取决于你的物理位置,但不会影响资源的运行时可用性。 对于本快速入门,请选择你附近的可用区域,或选择“中国东部 2”。
    名称 语言资源的名称。 此名称还将用于创建应用程序用于发送 API 请求的终结点 URL。
    定价层 语言资源的定价层。 可以使用免费 F0 层试用该服务,然后再升级到付费层进行生产。

    A screenshot showing resource creation details in the Azure portal.

  4. 确保选中“负责任 AI 通知”复选框。

  5. 在页面底部选择“查看 + 创建” 。

  6. 在显示的屏幕中,确保验证已通过,并且已正确输入信息。 然后选择“创建”。

获取密钥和终结点

然后需要从资源获取密钥和终结点,以便将应用程序连接到 API。 稍后需要在本快速入门中将密钥和终结点粘贴到代码中。

  1. 成功部署语言资源后,单击“后续步骤”下的“转到资源”按钮。

    A screenshot showing the next steps after a resource has deployed.

  2. 在资源的屏幕上,选择左侧导航菜单上的“密钥和终结点”。 在以下步骤中,你将使用其中一个密钥和终结点。

    A screenshot showing the keys and endpoint section for a resource.

创建环境变量

应用程序必须经过身份验证才能发送 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 控制台应用。 这会创建包含单个 C# 源文件的“Hello World”项目: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 应用程序,该应用程序可以识别文本示例中表达的情绪,并执行基于方面的情绪分析。

先决条件

设置

创建 Azure 资源

若要使用下面的代码示例,需要部署 Azure 资源。 此资源将包含一个密钥和终结点,用于对发送到语言服务的 API 调用进行身份验证。

  1. 使用以下链接通过 Azure 门户创建语言资源。 需要使用 Azure 订阅登录。

  2. 在显示的“选择其他功能”屏幕上,选择“继续创建资源”。

    A screenshot showing additional feature options in the Azure portal.

  3. 在“创建语言”屏幕中,提供以下信息:

    详细信息 说明
    订阅 资源将与之关联的订阅帐户。 从下拉菜单选择 Azure 订阅。
    资源组 资源组是存储所创建资源的容器。 选择“新建”来创建一个新的资源组。
    区域 语言资源的位置。 不同区域可能会导致延迟,具体取决于你的物理位置,但不会影响资源的运行时可用性。 对于本快速入门,请选择你附近的可用区域,或选择“中国东部 2”。
    名称 语言资源的名称。 此名称还将用于创建应用程序用于发送 API 请求的终结点 URL。
    定价层 语言资源的定价层。 可以使用免费 F0 层试用该服务,然后再升级到付费层进行生产。

    A screenshot showing resource creation details in the Azure portal.

  4. 确保选中“负责任 AI 通知”复选框。

  5. 在页面底部选择“查看 + 创建” 。

  6. 在显示的屏幕中,确保验证已通过,并且已正确输入信息。 然后选择“创建”。

获取密钥和终结点

然后需要从资源获取密钥和终结点,以便将应用程序连接到 API。 稍后需要在本快速入门中将密钥和终结点粘贴到代码中。

  1. 成功部署语言资源后,单击“后续步骤”下的“转到资源”按钮。

    A screenshot showing the next steps after a resource has deployed.

  2. 在资源的屏幕上,选择左侧导航菜单上的“密钥和终结点”。 在以下步骤中,你将使用其中一个密钥和终结点。

    A screenshot showing the keys and endpoint section for a resource.

创建环境变量

应用程序必须经过身份验证才能发送 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 应用程序,该应用程序可以识别文本示例中表达的情绪,并执行基于方面的情绪分析。

先决条件

设置

创建 Azure 资源

若要使用下面的代码示例,需要部署 Azure 资源。 此资源将包含一个密钥和终结点,用于对发送到语言服务的 API 调用进行身份验证。

  1. 使用以下链接通过 Azure 门户创建语言资源。 需要使用 Azure 订阅登录。

  2. 在显示的“选择其他功能”屏幕上,选择“继续创建资源”。

    A screenshot showing additional feature options in the Azure portal.

  3. 在“创建语言”屏幕中,提供以下信息:

    详细信息 说明
    订阅 资源将与之关联的订阅帐户。 从下拉菜单选择 Azure 订阅。
    资源组 资源组是存储所创建资源的容器。 选择“新建”来创建一个新的资源组。
    区域 语言资源的位置。 不同区域可能会导致延迟,具体取决于你的物理位置,但不会影响资源的运行时可用性。 对于本快速入门,请选择你附近的可用区域,或选择“中国东部 2”。
    名称 语言资源的名称。 此名称还将用于创建应用程序用于发送 API 请求的终结点 URL。
    定价层 语言资源的定价层。 可以使用免费 F0 层试用该服务,然后再升级到付费层进行生产。

    A screenshot showing resource creation details in the Azure portal.

  4. 确保选中“负责任 AI 通知”复选框。

  5. 在页面底部选择“查看 + 创建” 。

  6. 在显示的屏幕中,确保验证已通过,并且已正确输入信息。 然后选择“创建”。

获取密钥和终结点

然后需要从资源获取密钥和终结点,以便将应用程序连接到 API。 稍后需要在本快速入门中将密钥和终结点粘贴到代码中。

  1. 成功部署语言资源后,单击“后续步骤”下的“转到资源”按钮。

    A screenshot showing the next steps after a resource has deployed.

  2. 在资源的屏幕上,选择左侧导航菜单上的“密钥和终结点”。 在以下步骤中,你将使用其中一个密钥和终结点。

    A screenshot showing the keys and endpoint section for a resource.

创建环境变量

应用程序必须经过身份验证才能发送 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 文件创建一个 node 应用程序。

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 应用程序,该应用程序可以识别文本示例中表达的情绪,并执行基于方面的情绪分析。

先决条件

设置

创建 Azure 资源

若要使用下面的代码示例,需要部署 Azure 资源。 此资源将包含一个密钥和终结点,用于对发送到语言服务的 API 调用进行身份验证。

  1. 使用以下链接通过 Azure 门户创建语言资源。 需要使用 Azure 订阅登录。

  2. 在显示的“选择其他功能”屏幕上,选择“继续创建资源”。

    A screenshot showing additional feature options in the Azure portal.

  3. 在“创建语言”屏幕中,提供以下信息:

    详细信息 说明
    订阅 资源将与之关联的订阅帐户。 从下拉菜单选择 Azure 订阅。
    资源组 资源组是存储所创建资源的容器。 选择“新建”来创建一个新的资源组。
    区域 语言资源的位置。 不同区域可能会导致延迟,具体取决于你的物理位置,但不会影响资源的运行时可用性。 对于本快速入门,请选择你附近的可用区域,或选择“中国东部 2”。
    名称 语言资源的名称。 此名称还将用于创建应用程序用于发送 API 请求的终结点 URL。
    定价层 语言资源的定价层。 可以使用免费 F0 层试用该服务,然后再升级到付费层进行生产。

    A screenshot showing resource creation details in the Azure portal.

  4. 确保选中“负责任 AI 通知”复选框。

  5. 在页面底部选择“查看 + 创建” 。

  6. 在显示的屏幕中,确保验证已通过,并且已正确输入信息。 然后选择“创建”。

获取密钥和终结点

然后需要从资源获取密钥和终结点,以便将应用程序连接到 API。 稍后需要在本快速入门中将密钥和终结点粘贴到代码中。

  1. 成功部署语言资源后,单击“后续步骤”下的“转到资源”按钮。

    A screenshot showing the next steps after a resource has deployed.

  2. 在资源的屏幕上,选择左侧导航菜单上的“密钥和终结点”。 在以下步骤中,你将使用其中一个密钥和终结点。

    A screenshot showing the keys and endpoint section for a resource.

创建环境变量

应用程序必须经过身份验证才能发送 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. 在显示的“选择其他功能”屏幕上,选择“继续创建资源”。

    A screenshot showing additional feature options in the Azure portal.

  3. 在“创建语言”屏幕中,提供以下信息:

    详细信息 说明
    订阅 资源将与之关联的订阅帐户。 从下拉菜单选择 Azure 订阅。
    资源组 资源组是存储所创建资源的容器。 选择“新建”来创建一个新的资源组。
    区域 语言资源的位置。 不同区域可能会导致延迟,具体取决于你的物理位置,但不会影响资源的运行时可用性。 对于本快速入门,请选择你附近的可用区域,或选择“中国东部 2”。
    名称 语言资源的名称。 此名称还将用于创建应用程序用于发送 API 请求的终结点 URL。
    定价层 语言资源的定价层。 可以使用免费 F0 层试用该服务,然后再升级到付费层进行生产。

    A screenshot showing resource creation details in the Azure portal.

  4. 确保选中“负责任 AI 通知”复选框。

  5. 在页面底部选择“查看 + 创建” 。

  6. 在显示的屏幕中,确保验证已通过,并且已正确输入信息。 然后选择“创建”。

获取密钥和终结点

然后需要从资源获取密钥和终结点,以便将应用程序连接到 API。 稍后需要在本快速入门中将密钥和终结点粘贴到代码中。

  1. 成功部署语言资源后,单击“后续步骤”下的“转到资源”按钮。

    A screenshot showing the next steps after a resource has deployed.

  2. 在资源的屏幕上,选择左侧导航菜单上的“密钥和终结点”。 在以下步骤中,你将使用其中一个密钥和终结点。

    A screenshot showing the keys and endpoint section for a resource.

创建环境变量

应用程序必须经过身份验证才能发送 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

后续步骤