快速入门:检测命名实体 (NER)
参考文档 | 其他示例 | 包 (NuGet) | 库源代码
借助本快速入门,使用 .NET 客户端库创建命名实体识别 (NER) 应用程序。 在以下示例中,你将创建可在文本中识别已识别实体的 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 Azure.AI.TextAnalytics;
namespace Example
{
class Program
{
private static readonly AzureKeyCredential credentials = new AzureKeyCredential("replace-with-your-key-here");
private static readonly Uri endpoint = new Uri("replace-with-your-endpoint-here");
// Example method for extracting named entities from text
static void EntityRecognitionExample(TextAnalyticsClient client)
{
var response = client.RecognizeEntities("I had a wonderful trip to Seattle last week.");
Console.WriteLine("Named Entities:");
foreach (var entity in response.Value)
{
Console.WriteLine($"\tText: {entity.Text},\tCategory: {entity.Category},\tSub-Category: {entity.SubCategory}");
Console.WriteLine($"\t\tScore: {entity.ConfidenceScore:F2},\tLength: {entity.Length},\tOffset: {entity.Offset}\n");
}
}
static void Main(string[] args)
{
var client = new TextAnalyticsClient(endpoint, credentials);
EntityRecognitionExample(client);
Console.Write("Press any key to exit.");
Console.ReadKey();
}
}
}
输出
Named Entities:
Text: trip, Category: Event, Sub-Category:
Score: 0.74, Length: 4, Offset: 18
Text: Seattle, Category: Location, Sub-Category: GPE
Score: 1.00, Length: 7, Offset: 26
Text: last week, Category: DateTime, Sub-Category: DateRange
Score: 0.80, Length: 9, Offset: 34
参考文档 | 其他示例 | 包 (Maven) | 库源代码
借助本快速入门,使用 Java 客户端库创建命名实体识别 (NER) 应用程序。 在以下示例中,你将创建可在文本中识别已识别实体的 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);
recognizeEntitiesExample(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 in text
static void recognizeEntitiesExample(TextAnalyticsClient client)
{
// The text that need be analyzed.
String text = "I had a wonderful trip to Seattle last week.";
for (CategorizedEntity entity : client.recognizeEntities(text)) {
System.out.printf(
"Recognized entity: %s, entity category: %s, entity sub-category: %s, score: %s, offset: %s, length: %s.%n",
entity.getText(),
entity.getCategory(),
entity.getSubcategory(),
entity.getConfidenceScore(),
entity.getOffset(),
entity.getLength());
}
}
}
输出
Recognized entity: trip, entity category: Event, entity sub-category: null, score: 0.74, offset: 18, length: 4.
Recognized entity: Seattle, entity category: Location, entity sub-category: GPE, score: 1.0, offset: 26, length: 7.
Recognized entity: last week, entity category: DateTime, entity sub-category: DateRange, score: 0.8, offset: 34, length: 9.
借助本快速入门,使用 Node.js 客户端库创建命名实体识别 (NER) 应用程序。 在以下示例中,你将创建可在文本中识别已识别实体的 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 key = '<paste-your-key-here>';
const endpoint = '<paste-your-endpoint-here>';
//an example document for entity recognition
const documents = [ "Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800"];
//example of how to use the client library to recognize entities in a document.
async function main() {
console.log("== NER sample ==");
const client = new TextAnalysisClient(endpoint, new AzureKeyCredential(key));
const results = await client.analyze("EntityRecognition", documents);
for (const result of results) {
console.log(`- Document ${result.id}`);
if (!result.error) {
console.log("\tRecognized Entities:");
for (const entity of result.entities) {
console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
}
} else console.error("\tError:", result.error);
}
}
//call the main function
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
输出
Document ID: 0
Name: Microsoft Category: Organization Subcategory: N/A
Score: 0.29
Name: Bill Gates Category: Person Subcategory: N/A
Score: 0.78
Name: Paul Allen Category: Person Subcategory: N/A
Score: 0.82
Name: April 4, 1975 Category: DateTime Subcategory: Date
Score: 0.8
Name: 8800 Category: Quantity Subcategory: Number
Score: 0.8
Document ID: 1
Name: 21 Category: Quantity Subcategory: Number
Score: 0.8
Name: Seattle Category: Location Subcategory: GPE
Score: 0.25
借助本快速入门,使用 Python 客户端库创建命名实体识别 (NER) 应用程序。 在以下示例中,你将创建可在文本中识别已识别实体的 Python 应用程序。
提示
可以使用 Language Studio 来试用语言服务功能,而无需编写代码。
先决条件
- Azure 订阅 - 创建试用订阅
- Python 3.8 或更高版本
- 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
- 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
- 可以使用免费定价层 (
Free F0
) 试用该服务,然后再升级到付费层进行生产。
- 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。
设置
安装客户端库
在安装 Python 后,可以通过以下命令安装客户端库:
pip install azure-ai-textanalytics==5.2.0
代码示例
创建新的 Python 文件,并复制以下代码。 请记得将 key
变量替换为资源的密钥,并将 endpoint
变量替换为资源的终结点。 然后运行代码。
重要
转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。
重要
完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。
key = "paste-your-key-here"
endpoint = "paste-your-endpoint-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 from text
def entity_recognition_example(client):
try:
documents = ["I had a wonderful trip to Seattle last week."]
result = client.recognize_entities(documents = documents)[0]
print("Named Entities:\n")
for entity in result.entities:
print("\tText: \t", entity.text, "\tCategory: \t", entity.category, "\tSubCategory: \t", entity.subcategory,
"\n\tConfidence Score: \t", round(entity.confidence_score, 2), "\tLength: \t", entity.length, "\tOffset: \t", entity.offset, "\n")
except Exception as err:
print("Encountered exception. {}".format(err))
entity_recognition_example(client)
输出
Named Entities:
Text: trip Category: Event SubCategory: None
Confidence Score: 0.74 Length: 4 Offset: 18
Text: Seattle Category: Location SubCategory: GPE
Confidence Score: 1.0 Length: 7 Offset: 26
Text: last week Category: DateTime SubCategory: DateRange
Confidence Score: 0.8 Length: 9 Offset: 34
借助本快速入门,使用 REST API 发送命名实体识别 (NER) 请求。 在以下示例中,你将使用 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 值编辑这些命令。
命名实体提取 (NER)
- 将命令复制到文本编辑器中。
- 必要时在命令中进行如下更改:
- 将值
<your-language-resource-key>
替换为你的值。 - 将请求 URL 的第一部分 (
<your-language-resource-endpoint>
) 替换为你的终结点 URL。
- 将值
- 打开命令提示符窗口。
- 将文本编辑器中的命令粘贴到命令提示符窗口,然后运行命令。
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": "EntityRecognition",
"parameters": {
"modelVersion": "latest"
},
"analysisInput":{
"documents":[
{
"id":"1",
"language": "en",
"text": "I had a wonderful trip to Seattle last week."
}
]
}
}
'
JSON 响应
注意
- 正式版 API 和当前预览版 API 具有不同的响应格式。
- 预览版 API 自 API 版本
2023-04-15-preview
开始可用。
{
"kind": "EntityRecognitionResults",
"results": {
"documents": [{
"id": "1",
"entities": [{
"text": "trip",
"category": "Event",
"offset": 18,
"length": 4,
"confidenceScore": 0.74
}, {
"text": "Seattle",
"category": "Location",
"subcategory": "GPE",
"offset": 26,
"length": 7,
"confidenceScore": 1.0
}, {
"text": "last week",
"category": "DateTime",
"subcategory": "DateRange",
"offset": 34,
"length": 9,
"confidenceScore": 0.8
}],
"warnings": []
}],
"errors": [],
"modelVersion": "2021-06-01"
}
}
清理资源
如果想要清理并移除 Azure AI 服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。