快速入门:使用客户端库和 REST API 进行实体链接

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

借助本快速入门,使用 .NET 客户端库创建实体链接应用程序。 在以下示例中,你将创建一个 C# 应用程序,该应用程序可以识别和消除文本中实体的歧义。

提示

可以使用 Language Studio 来试用语言服务功能,而无需编写代码。

先决条件

  • Azure 订阅 - 创建试用订阅
  • Visual Studio IDE
  • 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (Free F0) 试用该服务,然后再升级到付费层进行生产。
  • 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。

设置

创建新的 .NET Core 应用程序

使用 Visual Studio IDE 创建新的 .NET Core 控制台应用。 这会创建包含单个 C# 源文件的“Hello World”项目:program.cs

右键单击解决方案资源管理器中的解决方案,然后选择“管理 NuGet 包”,以便安装客户端库。 在打开的包管理器中选择“浏览”,搜索 Azure.AI.TextAnalytics。 选择版本 5.2.0,然后选择“安装”。 也可使用包管理器控制台

代码示例

将以下代码复制到 program.cs 文件。 请记得将 key 变量替换为资源的密钥,并将 endpoint 变量替换为资源的终结点。 然后运行代码。

重要

转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。

using Azure;
using System;
using System.Globalization;
using Azure.AI.TextAnalytics;

namespace EntityLinkingExample
{
    class Program
    {
        private static readonly Uri endpoint = new Uri("replace-with-your-endpoint-here");
        private static readonly AzureKeyCredential credentials = new AzureKeyCredential("replace-with-your-key-here");
        
        // Example method for recognizing entities and providing a link to an online data source.
        static void EntityLinkingExample(TextAnalyticsClient client)
        {
            var response = client.RecognizeLinkedEntities(
                "Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, " +
                "to develop and sell BASIC interpreters for the Altair 8800. " +
                "During his career at Microsoft, Gates held the positions of chairman, " +
                "chief executive officer, president and chief software architect, " +
                "while also being the largest individual shareholder until May 2014.");
            Console.WriteLine("Linked Entities:");
            foreach (var entity in response.Value)
            {
                Console.WriteLine($"\tName: {entity.Name},\tID: {entity.DataSourceEntityId},\tURL: {entity.Url}\tData Source: {entity.DataSource}");
                Console.WriteLine("\tMatches:");
                foreach (var match in entity.Matches)
                {
                    Console.WriteLine($"\t\tText: {match.Text}");
                    Console.WriteLine($"\t\tScore: {match.ConfidenceScore:F2}\n");
                }
            }
        }

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

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

    }
}

输出

Linked Entities:
    Name: Microsoft,        ID: Microsoft,  URL: https://en.wikipedia.org/wiki/Microsoft    Data Source: Wikipedia
    Matches:
            Text: Microsoft
            Score: 0.55

            Text: Microsoft
            Score: 0.55

    Name: Bill Gates,       ID: Bill Gates, URL: https://en.wikipedia.org/wiki/Bill_Gates   Data Source: Wikipedia
    Matches:
            Text: Bill Gates
            Score: 0.63

            Text: Gates
            Score: 0.63

    Name: Paul Allen,       ID: Paul Allen, URL: https://en.wikipedia.org/wiki/Paul_Allen   Data Source: Wikipedia
    Matches:
            Text: Paul Allen
            Score: 0.60

    Name: April 4,  ID: April 4,    URL: https://en.wikipedia.org/wiki/April_4      Data Source: Wikipedia
    Matches:
            Text: April 4
            Score: 0.32

    Name: BASIC,    ID: BASIC,      URL: https://en.wikipedia.org/wiki/BASIC        Data Source: Wikipedia
    Matches:
            Text: BASIC
            Score: 0.33

    Name: Altair 8800,      ID: Altair 8800,        URL: https://en.wikipedia.org/wiki/Altair_8800  Data Source: Wikipedia
    Matches:
            Text: Altair 8800
            Score: 0.88

清理资源

如果想要清理并移除 Azure AI 服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。

后续步骤

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

借助本快速入门,使用 Java 客户端库创建实体链接应用程序。 在以下示例中,你将创建一个 Java 应用程序,该应用程序可以识别和消除文本中实体的歧义。

提示

可以使用 Language Studio 来试用语言服务功能,而无需编写代码。

先决条件

  • Azure 订阅 - 创建试用订阅
  • Java 开发工具包 (JDK) 版本 8 或更高版本
  • 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (Free F0) 试用该服务,然后再升级到付费层进行生产。
  • 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。

设置

添加客户端库

在首选 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 文件。 打开该文件,并复制以下代码。 请记得将 key 变量替换为资源的密钥,并将 endpoint 变量替换为资源的终结点。 然后运行代码。

重要

转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。

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 {

    private static String KEY = "replace-with-your-key-here";
    private static String ENDPOINT = "replace-with-your-endpoint-here";

    public static void main(String[] args) {
        TextAnalyticsClient client = authenticateClient(KEY, ENDPOINT);
        recognizeLinkedEntitiesExample(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 recognizing entities and providing a link to an online data source
    static void recognizeLinkedEntitiesExample(TextAnalyticsClient client)
    {
        // The text that need be analyzed.
        String text = "Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, " +
                "to develop and sell BASIC interpreters for the Altair 8800. " +
                "During his career at Microsoft, Gates held the positions of chairman, " +
                "chief executive officer, president and chief software architect, " +
                "while also being the largest individual shareholder until May 2014.";

        System.out.printf("Linked Entities:%n");
        for (LinkedEntity linkedEntity : client.recognizeLinkedEntities(text)) {
            System.out.printf("Name: %s, ID: %s, URL: %s, Data Source: %s.%n",
                    linkedEntity.getName(),
                    linkedEntity.getDataSourceEntityId(),
                    linkedEntity.getUrl(),
                    linkedEntity.getDataSource());
            System.out.printf("Matches:%n");
            for (LinkedEntityMatch linkedEntityMatch : linkedEntity.getMatches()) {
                System.out.printf("Text: %s, Score: %.2f, Offset: %s, Length: %s%n",
                        linkedEntityMatch.getText(),
                        linkedEntityMatch.getConfidenceScore(),
                        linkedEntityMatch.getOffset(),
                        linkedEntityMatch.getLength());
            }
        }
    }
}

输出

Linked Entities:

Name: Microsoft, ID: Microsoft, URL: https://en.wikipedia.org/wiki/Microsoft, Data Source: Wikipedia.
Matches:
Text: Microsoft, Score: 0.55, Offset: 0, Length: 9
Text: Microsoft, Score: 0.55, Offset: 150, Length: 9
Name: Bill Gates, ID: Bill Gates, URL: https://en.wikipedia.org/wiki/Bill_Gates, Data Source: Wikipedia.
Matches:
Text: Bill Gates, Score: 0.63, Offset: 25, Length: 10
Text: Gates, Score: 0.63, Offset: 161, Length: 5
Name: Paul Allen, ID: Paul Allen, URL: https://en.wikipedia.org/wiki/Paul_Allen, Data Source: Wikipedia.
Matches:
Text: Paul Allen, Score: 0.60, Offset: 40, Length: 10
Name: April 4, ID: April 4, URL: https://en.wikipedia.org/wiki/April_4, Data Source: Wikipedia.
Matches:
Text: April 4, Score: 0.32, Offset: 54, Length: 7
Name: BASIC, ID: BASIC, URL: https://en.wikipedia.org/wiki/BASIC, Data Source: Wikipedia.
Matches:
Text: BASIC, Score: 0.33, Offset: 89, Length: 5
Name: Altair 8800, ID: Altair 8800, URL: https://en.wikipedia.org/wiki/Altair_8800, Data Source: Wikipedia.
Matches:
Text: Altair 8800, Score: 0.88, Offset: 116, Length: 11

清理资源

如果想要清理并移除 Azure AI 服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。

后续步骤

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

借助本快速入门,使用 Node.js 客户端库创建实体链接应用程序。 在以下示例中,你将创建一个 JavaScript 应用程序,该应用程序可以识别和消除文本中实体的歧义。

提示

可以使用 Language Studio 来试用语言服务功能,而无需编写代码。

先决条件

  • Azure 订阅 - 创建试用订阅
  • Node.js v14 LTS 或更高版本
  • 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (Free F0) 试用该服务,然后再升级到付费层进行生产。
  • 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。

设置

创建新的 Node.js 应用程序

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。

mkdir myapp 

cd myapp

运行 npm init 命令以使用 package.json 文件创建一个 node 应用程序。

npm init

安装客户端库

安装 npm 包:

npm install @azure/ai-language-text

代码示例

打开该文件,并复制以下代码。 请记得将 key 变量替换为资源的密钥,并将 endpoint 变量替换为资源的终结点。 然后运行代码。

重要

转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。

"use strict";

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");
const endpoint = '<paste-your-endpoint-here>';
const key = '<paste-your-key-here>';
//example sentence for recognizing entities
const documents = ["Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975."];

//example of how to use the client to perform entity linking on a document
async function main() {
    console.log("== Entity linking sample ==");
  
    const client = new TextAnalysisClient(endpoint, new AzureKeyCredential(key));
  
    const results = await client.analyze("EntityLinking", documents);
  
    for (const result of results) {
      console.log(`- Document ${result.id}`);
      if (!result.error) {
        console.log("\tEntities:");
        for (const entity of result.entities) {
          console.log(
            `\t- Entity ${entity.name}; link ${entity.url}; datasource: ${entity.dataSource}`
          );
          console.log("\t\tMatches:");
          for (const match of entity.matches) {
            console.log(
              `\t\t- Entity appears as "${match.text}" (confidence: ${match.confidenceScore}`
            );
          }
        }
      } else {
        console.error("  Error:", result.error);
      }
    }
  }

//call the main function
main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

输出

== Entity linking sample ==
- Document 0
    Entities:
    - Entity Microsoft; link https://en.wikipedia.org/wiki/Microsoft; datasource: Wikipedia
            Matches:
            - Entity appears as "Microsoft" (confidence: 0.48
    - Entity Bill Gates; link https://en.wikipedia.org/wiki/Bill_Gates; datasource: Wikipedia
            Matches:
            - Entity appears as "Bill Gates" (confidence: 0.52
    - Entity Paul Allen; link https://en.wikipedia.org/wiki/Paul_Allen; datasource: Wikipedia
            Matches:
            - Entity appears as "Paul Allen" (confidence: 0.54
    - Entity April 4; link https://en.wikipedia.org/wiki/April_4; datasource: Wikipedia
            Matches:
            - Entity appears as "April 4" (confidence: 0.38

清理资源

如果想要清理并移除 Azure AI 服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。

后续步骤

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

借助本快速入门,使用 Python 客户端库创建实体链接应用程序。 在以下示例中,你将创建一个 Python 应用程序,该应用程序可以识别和消除文本中实体的歧义。

提示

可以使用 Language Studio 来试用语言服务功能,而无需编写代码。

先决条件

  • Azure 订阅 - 创建试用订阅
  • Python 3.7 或更高版本
  • 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (Free F0) 试用该服务,然后再升级到付费层进行生产。
  • 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。

设置

安装客户端库

在安装 Python 后,可以通过以下命令安装客户端库:

pip install azure-ai-textanalytics==5.2.0

代码示例

创建新的 Python 文件,并复制以下代码。 请记得将 key 变量替换为资源的密钥,并将 endpoint 变量替换为资源的终结点。 然后运行代码。

重要

转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。

endpoint = "paste-your-endpoint-here"
key = "paste-your-key-here"

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(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint, 
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

# Example function for recognizing entities and providing a link to an online data source.
def entity_linking_example(client):

    try:
        documents = ["""Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, 
        to develop and sell BASIC interpreters for the Altair 8800. 
        During his career at Microsoft, Gates held the positions of chairman,
        chief executive officer, president and chief software architect, 
        while also being the largest individual shareholder until May 2014."""]
        result = client.recognize_linked_entities(documents = documents)[0]

        print("Linked Entities:\n")
        for entity in result.entities:
            print("\tName: ", entity.name, "\tId: ", entity.data_source_entity_id, "\tUrl: ", entity.url,
            "\n\tData Source: ", entity.data_source)
            print("\tMatches:")
            for match in entity.matches:
                print("\t\tText:", match.text)
                print("\t\tConfidence Score: {0:.2f}".format(match.confidence_score))
                print("\t\tOffset: {}".format(match.offset))
                print("\t\tLength: {}".format(match.length))
            
    except Exception as err:
        print("Encountered exception. {}".format(err))
entity_linking_example(client)

输出

Linked Entities:
    
    Name:  Microsoft        Id:  Microsoft  Url:  https://en.wikipedia.org/wiki/Microsoft
    Data Source:  Wikipedia
    Matches:
            Text: Microsoft
            Confidence Score: 0.55
            Offset: 0
            Length: 9
            Text: Microsoft
            Confidence Score: 0.55
            Offset: 168
            Length: 9
    Name:  Bill Gates       Id:  Bill Gates         Url:  https://en.wikipedia.org/wiki/Bill_Gates
    Data Source:  Wikipedia
    Matches:
            Text: Bill Gates
            Confidence Score: 0.63
            Offset: 25
            Length: 10
            Text: Gates
            Confidence Score: 0.63
            Offset: 179
            Length: 5
    Name:  Paul Allen       Id:  Paul Allen         Url:  https://en.wikipedia.org/wiki/Paul_Allen
    Data Source:  Wikipedia
    Matches:
            Text: Paul Allen
            Confidence Score: 0.60
            Offset: 40
            Length: 10
    Name:  April 4  Id:  April 4    Url:  https://en.wikipedia.org/wiki/April_4
    Data Source:  Wikipedia
    Matches:
            Text: BASIC
            Confidence Score: 0.33
            Offset: 98
            Length: 5
    Name:  Altair 8800      Id:  Altair 8800        Url:  https://en.wikipedia.org/wiki/Altair_8800
    Data Source:  Wikipedia
    Matches:
            Text: Altair 8800
            Confidence Score: 0.88
            Offset: 125
            Length: 11

清理资源

如果想要清理并移除 Azure AI 服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。

后续步骤

参考文档

借助本快速入门,使用 REST API 发送实体链接请求。 在以下示例中,你将使用 cURL 来识别和消除文本中实体的歧义。

提示

可以使用 Language Studio 来试用语言服务功能,而无需编写代码。

先决条件

  • 最新版本的 cURL
  • 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (Free F0) 试用该服务,然后再升级到付费层进行生产。

注意

  • 以下 BASH 示例使用 \ 行继续符。 如果你的控制台或终端使用不同的行继续符,请使用该字符。
  • 可以在 GitHub 上找到特定于语言的示例。
  • 访问 Azure 门户,并找到之前在先决条件部分中创建的语言资源的密钥和终结点。 它们将位于资源的“密钥和终结点”页的“资源管理”下。 然后,将以下代码中的字符串替换为你的密钥和终结点。 若要调用 API,需要以下信息:
参数 (parameter) 说明
-X POST <endpoint> 指定用于访问 API 的终结点。
-H Content-Type: application/json 用于发送 JSON 数据的内容类型。
-H "Ocp-Apim-Subscription-Key:<key> 指定用于访问 API 的密钥。
-d <documents> 包含要发送的文档的 JSON。

以下 cURL 命令从 BASH shell 中执行。 请使用自己的资源名称、资源密钥和 JSON 值编辑这些命令。

实体链接

  1. 将命令复制到文本编辑器中。
  2. 必要时在命令中进行如下更改:
    1. 将值 <your-language-resource-key> 替换为你的值。
    2. 将请求 URL 的第一部分 (<your-language-resource-endpoint>) 替换为你的终结点 URL。
  3. 打开命令提示符窗口。
  4. 将文本编辑器中的命令粘贴到命令提示符窗口,然后运行命令。
curl -i -X POST https://<your-language-resource-endpoint>/language/:analyze-text?api-version=2022-05-01 \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key: <your-language-resource-key>" \
-d \
'
{
    "kind": "EntityLinking",
    "parameters": {
        "modelVersion": "latest"
    },
    "analysisInput":{
        "documents":[
            {
                "id":"1",
                "language":"en",
                "text": "Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975."
            }
        ]
    }
}
'

JSON 响应

{
	"kind": "EntityLinkingResults",
	"results": {
		"documents": [{
			"id": "1",
			"entities": [{
				"bingId": "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85",
				"name": "Microsoft",
				"matches": [{
					"text": "Microsoft",
					"offset": 0,
					"length": 9,
					"confidenceScore": 0.48
				}],
				"language": "en",
				"id": "Microsoft",
				"url": "https://en.wikipedia.org/wiki/Microsoft",
				"dataSource": "Wikipedia"
			}, {
				"bingId": "0d47c987-0042-5576-15e8-97af601614fa",
				"name": "Bill Gates",
				"matches": [{
					"text": "Bill Gates",
					"offset": 25,
					"length": 10,
					"confidenceScore": 0.52
				}],
				"language": "en",
				"id": "Bill Gates",
				"url": "https://en.wikipedia.org/wiki/Bill_Gates",
				"dataSource": "Wikipedia"
			}, {
				"bingId": "df2c4376-9923-6a54-893f-2ee5a5badbc7",
				"name": "Paul Allen",
				"matches": [{
					"text": "Paul Allen",
					"offset": 40,
					"length": 10,
					"confidenceScore": 0.54
				}],
				"language": "en",
				"id": "Paul Allen",
				"url": "https://en.wikipedia.org/wiki/Paul_Allen",
				"dataSource": "Wikipedia"
			}, {
				"bingId": "52535f87-235e-b513-54fe-c03e4233ac6e",
				"name": "April 4",
				"matches": [{
					"text": "April 4",
					"offset": 54,
					"length": 7,
					"confidenceScore": 0.38
				}],
				"language": "en",
				"id": "April 4",
				"url": "https://en.wikipedia.org/wiki/April_4",
				"dataSource": "Wikipedia"
			}],
			"warnings": []
		}],
		"errors": [],
		"modelVersion": "2021-06-01"
	}
}

清理资源

如果想要清理并移除 Azure AI 服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。

后续步骤