Azure.AI.TextAnalytics 5.3.0
Prefix Reserved
dotnet add package Azure.AI.TextAnalytics --version 5.3.0
NuGet\Install-Package Azure.AI.TextAnalytics -Version 5.3.0
<PackageReference Include="Azure.AI.TextAnalytics" Version="5.3.0" />
paket add Azure.AI.TextAnalytics --version 5.3.0
#r "nuget: Azure.AI.TextAnalytics, 5.3.0"
// Install Azure.AI.TextAnalytics as a Cake Addin #addin nuget:?package=Azure.AI.TextAnalytics&version=5.3.0 // Install Azure.AI.TextAnalytics as a Cake Tool #tool nuget:?package=Azure.AI.TextAnalytics&version=5.3.0
针对 .NET 的 Azure 认知服务文本分析客户端库
文本分析是 Azure 认知服务语言的一部分,这是一个基于云的服务,它提供了自然语言处理(NLP)功能,用于理解和分析文本。此客户端库提供了以下功能
- 语言检测
- 情感分析
- 关键词提取
- 命名实体识别(NER)
- 个人身份信息(PII)实体识别
- 实体链接
- 健康领域的文本分析
- 自定义命名实体识别(Custom NER)
- 自定义文本分类
- 提取式文本摘要
- 抽象式文本摘要
源代码 | 包(NuGet) | API参考文档 | 产品文档 | 示例
入门
安装包
使用 NuGet 安装 Azure Text Analytics 客户端库。
dotnet add package Azure.AI.TextAnalytics
此表显示了服务 SDK 版本与支持的 API 版本之间的关系。
请注意,
5.2.0是针对 Azure 认知服务语言 API 的客户端库的第一个稳定版本,它包括 Text Analytics 客户端库中存在的文本分析和自然语言处理功能。此外,服务 API 已从语义版本更改为基于日期的版本。
| SDK 版本 | 服务支持的 API 版本 |
|---|---|
| 5.3.X | 3.0,3.1,2022-05-01,2023-04-01(默认) |
| 5.2.X | 3.0,3.1,2022-05-01(默认) |
| 5.1.X | 3.0,3.1(默认) |
| 5.0.X | 3.0 |
| 1.0.X | 3.0 |
先决条件
- 一个 Azure 订阅。
- 现有的认知服务或语言服务资源。
创建认知服务资源或语言服务资源
Azure 认知服务语言支持多服务和单服务访问。如果您计划通过单个端点和 API 密钥访问多个认知服务,请创建认知服务资源。若仅要访问语言服务的功能,请创建语言服务资源。
您可以通过 Azure 门户 或通过以下步骤创建资源:在 此文档 中使用 Azure CLI 进行创建。
验证客户端
使用客户端库与该服务交互从创建一个 TextAnalyticsClient 类的实例开始。您需要一个 端点,以及一个 API 密钥 或 TokenCredential 来创建客户端对象。有关认知服务身份验证的更多信息,请参阅 验证 Azure 认知服务请求。
获取 API 密钥
您可以从 Azure 门户 中的认知服务资源或语言服务资源配置信息中获取 端点 和 API 密钥。
或者,您可以使用下面的 Azure CLI 片段从语言服务资源中获取 API 密钥。
az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>
使用 API 密钥凭据创建 TextAnalyticsClient
一旦您有了 API 密钥的值,请创建一个 AzureKeyCredential。这将允许您更新 API 密钥而无需创建新的客户端。
使用端点 AzureKeyCredential 的值,您可以为 TextAnalyticsClient 创建。
Uri endpoint = new("<endpoint>");
AzureKeyCredential credential = new("<apiKey>");
TextAnalyticsClient client = new(endpoint, credential);
使用 Azure Active Directory 凭据创建 TextAnalyticsClient
此入门指南的大多数示例中使用客户端 API 密钥身份验证,但您也可以使用 Azure Identity 库 通过 Azure Active Directory 进行身份验证。请注意,区域端点不支持 AAD 身份验证。为了使用此类身份验证,为您的资源创建一个 自定义子域。
要使用以下显示的 DefaultAzureCredential 提供器或由 Azure SDK 提供的其他凭证提供器,请安装 Azure.Identity 包。
dotnet add package Azure.Identity
您还需要 注册一个新的 AAD 应用程序 并通过将 "Cognitive Services User" 角色分配给您的服务主体来 授权访问 语言服务。
将 AAD 应用程序的客户端 ID、租户 ID 和客户端密钥的值设置为环境变量:AZURE_CLIENT_ID、AZURE_TENANT_ID、AZURE_CLIENT_SECRET。
Uri endpoint = new("<endpoint>");
TextAnalyticsClient client = new(endpoint, new DefaultAzureCredential());
关键概念
TextAnalyticsClient
TextAnalyticsClient 是使用 Text Analytics 客户端库的开发商的主要接口。它提供同步和异步操作,以访问特定文本分析用途,例如语言检测或关键短语提取。
输入
一个 文档 是语言服务中预测模型要分析的单一输入单元。对 TextAnalyticsClient 的操作可以接受一个要分析的单一文档或文档集合,作为批量操作。有关文档长度限制、最大批量大小和支持的文本编码,请参阅这里。
对多个文档的操作
对于每个支持的操作,TextAnalyticsClient 提供了一个接受文档批次(作为字符串)的方法,或批量接受 TextDocumentInput 或 DetectLanguageInput 对象的方法。此方法允许调用者给每个文档分配一个唯一的 ID,指示批次中的文档使用不同的语言,或提供有关文档语言的区域提示。
注意:建议在生产环境中使用批量方法,因为它们允许您通过单个请求发送多个文档。这与逐个发送请求相比性能更好。
返回值
返回值,例如 AnalyzeSentimentResult,是 Text Analytics 操作的结果,包含有关单个文档的预测或预测。操作返回值亦可能包括有关文档及其处理方式的信息。
返回值集合
返回值集合,例如 AnalyzeSentimentResultCollection,是一组操作结果,其中每个对应于输入批量中提供的一个文档。文档及其结果将具有输入和结果集合中的相同索引。返回值还包含一个 HasError 属性,允许识别针对给定文档的操作是成功还是失败。它还可能包括有关文档批量的信息及其处理方式。
长运行操作
对于需要较长时间执行的大型文档,这些操作实现为 长运行操作。长运行操作包括向服务发送初始请求以启动操作,然后以一定间隔轮询服务以确定操作是否已完成或失败,以及如果操作已成功,获取结果。
对于 Azure SDK 中的长运行操作,客户端公开一个 Start<operation-name> 方法,返回一个 Operation<T> 或 PageableOperation<T>。您可以使用扩展方法 WaitForCompletionAsync() 等待操作完成并获取其结果。有关使用长运行操作的代码示例,请参阅下面。
线程安全
我们保证所有客户端实例方法都是线程安全的,并且彼此独立(《[线程安全指南](https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-service-methods-thread-safety)》)。这确保了重用客户端实例的建议始终是安全的,即使在跨线程的情况下也是。
其他概念
例子
同步例子
异步例子
检测语言
运行一个预测模型以确定传入的文档或文档批次的语言。
string document =
"Este documento está escrito en un lenguaje diferente al inglés. Su objectivo es demostrar cómo"
+ " invocar el método de Detección de Lenguaje del servicio de Text Analytics en Microsoft Azure."
+ " También muestra cómo acceder a la información retornada por el servicio. Esta funcionalidad es"
+ " útil para los sistemas de contenido que recopilan texto arbitrario, donde el lenguaje no se conoce"
+ " de antemano. Puede usarse para detectar una amplia gama de lenguajes, variantes, dialectos y"
+ " algunos idiomas regionales o culturales.";
try
{
Response<DetectedLanguage> response = client.DetectLanguage(document);
DetectedLanguage language = response.Value;
Console.WriteLine($"Detected language is {language.Name} with a confidence score of {language.ConfidenceScore}.");
}
catch (RequestFailedException exception)
{
Console.WriteLine($"Error Code: {exception.ErrorCode}");
Console.WriteLine($"Message: {exception.Message}");
}
有关使用生产推荐选项 DetectLanguageBatch 的示例,请参阅此处。
请参阅服务文档,以了解有关语言检测的概念性讨论。
分析情感
运行一个预测模型以确定传入的文档或文档批次中包含的积极、消极、中性或混合情感。
string document =
"I had the best day of my life. I decided to go sky-diving and it made me appreciate my whole life so"
+ "much more. I developed a deep-connection with my instructor as well, and I feel as if I've made a"
+ "life-long friend in her.";
try
{
Response<DocumentSentiment> response = client.AnalyzeSentiment(document);
DocumentSentiment docSentiment = response.Value;
Console.WriteLine($"Document sentiment is {docSentiment.Sentiment} with: ");
Console.WriteLine($" Positive confidence score: {docSentiment.ConfidenceScores.Positive}");
Console.WriteLine($" Neutral confidence score: {docSentiment.ConfidenceScores.Neutral}");
Console.WriteLine($" Negative confidence score: {docSentiment.ConfidenceScores.Negative}");
}
catch (RequestFailedException exception)
{
Console.WriteLine($"Error Code: {exception.ErrorCode}");
Console.WriteLine($"Message: {exception.Message}");
}
有关使用生产推荐选项 AnalyzeSentimentBatch 的示例,请参阅此处。
要获取有关产品/服务目标的意见的更详细的信息,也称为自然语言处理中的基于方面的情感分析,请参阅关于带意见挖掘的情感分析的示例此处。
请参阅服务文档,以了解有关情感分析的概念性讨论。
提取关键短语
运行一个模型以识别在传入的文档或文档批次中找到的一组重要短语。
string document =
"My cat might need to see a veterinarian. It has been sneezing more than normal, and although my"
+ " little sister thinks it is funny, I am worried it has the cold that I got last week. We are going"
+ " to call tomorrow and try to schedule an appointment for this week. Hopefully it will be covered by"
+ " the cat's insurance. It might be good to not let it sleep in my room for a while.";
try
{
Response<KeyPhraseCollection> response = client.ExtractKeyPhrases(document);
KeyPhraseCollection keyPhrases = response.Value;
Console.WriteLine($"Extracted {keyPhrases.Count} key phrases:");
foreach (string keyPhrase in keyPhrases)
{
Console.WriteLine($" {keyPhrase}");
}
}
catch (RequestFailedException exception)
{
Console.WriteLine($"Error Code: {exception.ErrorCode}");
Console.WriteLine($"Message: {exception.Message}");
}
有关使用生产推荐选项 ExtractKeyPhrasesBatch 的示例,请参阅此处。
请参阅服务文档,以了解有关关键短语提取的概念性讨论。
识别命名实体
运行预测模型来识别在传入文档或文档集中存在的命名实体的集合,并将这些实体分类到人、地点或组织等类别中。有关可用的类别信息,请参阅文本分析命名实体类别。
string document =
"We love this trail and make the trip every year. The views are breathtaking and well worth the hike!"
+ " Yesterday was foggy though, so we missed the spectacular views. We tried again today and it was"
+ " amazing. Everyone in my family liked the trail although it was too challenging for the less"
+ " athletic among us. Not necessarily recommended for small children. A hotel close to the trail"
+ " offers services for childcare in case you want that.";
try
{
Response<CategorizedEntityCollection> response = client.RecognizeEntities(document);
CategorizedEntityCollection entitiesInDocument = response.Value;
Console.WriteLine($"Recognized {entitiesInDocument.Count} entities:");
foreach (CategorizedEntity entity in entitiesInDocument)
{
Console.WriteLine($" Text: {entity.Text}");
Console.WriteLine($" Offset: {entity.Offset}");
Console.WriteLine($" Length: {entity.Length}");
Console.WriteLine($" Category: {entity.Category}");
if (!string.IsNullOrEmpty(entity.SubCategory))
Console.WriteLine($" SubCategory: {entity.SubCategory}");
Console.WriteLine($" Confidence score: {entity.ConfidenceScore}");
Console.WriteLine();
}
}
catch (RequestFailedException exception)
{
Console.WriteLine($"Error Code: {exception.ErrorCode}");
Console.WriteLine($"Message: {exception.Message}");
}
有关使用生产推荐的选项RecognizeEntitiesBatch的示例,请参阅此处。
有关命名实体识别的概念讨论,请参阅服务文档。
识别个人身份信息实体
运行预测模型来识别在传入文档或文档集中发现的包含个人身份信息的实体集合,并将这些实体分类到如美国社会安全号码、驾照号码或信用卡号码等类别。
string document =
"Parker Doe has repaid all of their loans as of 2020-04-25. Their SSN is 859-98-0987. To contact them,"
+ " use their phone number 800-102-1100. They are originally from Brazil and have document ID number"
+ " 998.214.865-68.";
try
{
Response<PiiEntityCollection> response = client.RecognizePiiEntities(document);
PiiEntityCollection entities = response.Value;
Console.WriteLine($"Redacted Text: {entities.RedactedText}");
Console.WriteLine();
Console.WriteLine($"Recognized {entities.Count} PII entities:");
foreach (PiiEntity entity in entities)
{
Console.WriteLine($" Text: {entity.Text}");
Console.WriteLine($" Category: {entity.Category}");
if (!string.IsNullOrEmpty(entity.SubCategory))
Console.WriteLine($" SubCategory: {entity.SubCategory}");
Console.WriteLine($" Confidence score: {entity.ConfidenceScore}");
Console.WriteLine();
}
}
catch (RequestFailedException exception)
{
Console.WriteLine($"Error Code: {exception.ErrorCode}");
Console.WriteLine($"Message: {exception.Message}");
}
有关使用生产推荐的选项RecognizePiiEntitiesBatch的示例,请参阅此处。
请参阅服务文档了解支持的PII实体类型。
识别链接实体
运行预测模型来识别在传入文档或文档集中发现的实体集合,并将这些实体的信息链接到知名知识库中的对应条目。
string document =
"Microsoft was founded by Bill Gates with some friends he met at Harvard. One of his friends, Steve"
+ " Ballmer, eventually became CEO after Bill Gates as well. Steve Ballmer eventually stepped down as"
+ " CEO of Microsoft, and was succeeded by Satya Nadella. Microsoft originally moved its headquarters"
+ " to Bellevue, Washington in Januaray 1979, but is now headquartered in Redmond.";
try
{
Response<LinkedEntityCollection> response = client.RecognizeLinkedEntities(document);
LinkedEntityCollection linkedEntities = response.Value;
Console.WriteLine($"Recognized {linkedEntities.Count} entities:");
foreach (LinkedEntity linkedEntity in linkedEntities)
{
Console.WriteLine($" Name: {linkedEntity.Name}");
Console.WriteLine($" Language: {linkedEntity.Language}");
Console.WriteLine($" Data Source: {linkedEntity.DataSource}");
Console.WriteLine($" URL: {linkedEntity.Url}");
Console.WriteLine($" Entity Id in Data Source: {linkedEntity.DataSourceEntityId}");
foreach (LinkedEntityMatch match in linkedEntity.Matches)
{
Console.WriteLine($" Match Text: {match.Text}");
Console.WriteLine($" Offset: {match.Offset}");
Console.WriteLine($" Length: {match.Length}");
Console.WriteLine($" Confidence score: {match.ConfidenceScore}");
}
Console.WriteLine();
}
}
catch (RequestFailedException exception)
{
Console.WriteLine($"Error Code: {exception.ErrorCode}");
Console.WriteLine($"Message: {exception.Message}");
}
有关使用生产推荐的选项RecognizeLinkedEntitiesBatch的示例,请参阅此处。
请参阅服务文档了解实体链接的概念。
异步检测语言
运行一个预测模型以确定传入的文档或文档批次的语言。
string document =
"Este documento está escrito en un lenguaje diferente al inglés. Su objectivo es demostrar cómo"
+ " invocar el método de Detección de Lenguaje del servicio de Text Analytics en Microsoft Azure."
+ " También muestra cómo acceder a la información retornada por el servicio. Esta funcionalidad es"
+ " útil para los sistemas de contenido que recopilan texto arbitrario, donde el lenguaje no se conoce"
+ " de antemano. Puede usarse para detectar una amplia gama de lenguajes, variantes, dialectos y"
+ " algunos idiomas regionales o culturales.";
try
{
Response<DetectedLanguage> response = await client.DetectLanguageAsync(document);
DetectedLanguage language = response.Value;
Console.WriteLine($"Detected language is {language.Name} with a confidence score of {language.ConfidenceScore}.");
}
catch (RequestFailedException exception)
{
Console.WriteLine($"Error Code: {exception.ErrorCode}");
Console.WriteLine($"Message: {exception.Message}");
}
异步识别命名实体
运行预测模型来识别在传入文档或文档集中存在的命名实体的集合,并将这些实体分类到人、地点或组织等类别中。有关可用的类别信息,请参阅文本分析命名实体类别。
string document =
"We love this trail and make the trip every year. The views are breathtaking and well worth the hike!"
+ " Yesterday was foggy though, so we missed the spectacular views. We tried again today and it was"
+ " amazing. Everyone in my family liked the trail although it was too challenging for the less"
+ " athletic among us. Not necessarily recommended for small children. A hotel close to the trail"
+ " offers services for childcare in case you want that.";
try
{
Response<CategorizedEntityCollection> response = await client.RecognizeEntitiesAsync(document);
CategorizedEntityCollection entitiesInDocument = response.Value;
Console.WriteLine($"Recognized {entitiesInDocument.Count} entities:");
foreach (CategorizedEntity entity in entitiesInDocument)
{
Console.WriteLine($" Text: {entity.Text}");
Console.WriteLine($" Offset: {entity.Offset}");
Console.WriteLine($" Length: {entity.Length}");
Console.WriteLine($" Category: {entity.Category}");
if (!string.IsNullOrEmpty(entity.SubCategory))
Console.WriteLine($" SubCategory: {entity.SubCategory}");
Console.WriteLine($" Confidence score: {entity.ConfidenceScore}");
Console.WriteLine();
}
}
catch (RequestFailedException exception)
{
Console.WriteLine($"Error Code: {exception.ErrorCode}");
Console.WriteLine($"Message: {exception.Message}");
}
异步分析医疗实体
健康文本分析是一个容器化服务,可从非结构化文本(如医生的笔记、出院总结、临床文档和电子健康记录)中提取和标记相关的医疗信息。更多信息请参阅如何:使用健康文本分析。
string documentA =
"RECORD #333582770390100 | MH | 85986313 | | 054351 | 2/14/2001 12:00:00 AM |"
+ " CORONARY ARTERY DISEASE | Signed | DIS |"
+ Environment.NewLine
+ " Admission Date: 5/22/2001 Report Status: Signed Discharge Date: 4/24/2001"
+ " ADMISSION DIAGNOSIS: CORONARY ARTERY DISEASE."
+ Environment.NewLine
+ " HISTORY OF PRESENT ILLNESS: The patient is a 54-year-old gentleman with a history of progressive"
+ " angina over the past several months. The patient had a cardiac catheterization in July of this"
+ " year revealing total occlusion of the RCA and 50% left main disease, with a strong family history"
+ " of coronary artery disease with a brother dying at the age of 52 from a myocardial infarction and"
+ " another brother who is status post coronary artery bypass grafting. The patient had a stress"
+ " echocardiogram done on July, 2001, which showed no wall motion abnormalities, but this was a"
+ " difficult study due to body habitus. The patient went for six minutes with minimal ST depressions"
+ " in the anterior lateral leads, thought due to fatigue and wrist pain, his anginal equivalent. Due"
+ " to the patient'sincreased symptoms and family history and history left main disease with total"
+ " occasional of his RCA was referred for revascularization with open heart surgery.";
string documentB = "Prescribed 100mg ibuprofen, taken twice daily.";
// Prepare the input of the text analysis operation. You can add multiple documents to this list and
// perform the same operation on all of them simultaneously.
List<string> batchedDocuments = new()
{
documentA,
documentB
};
// Perform the text analysis operation.
AnalyzeHealthcareEntitiesOperation operation = await client.AnalyzeHealthcareEntitiesAsync(WaitUntil.Completed, batchedDocuments);
Console.WriteLine($"The operation has completed.");
Console.WriteLine();
// View the operation status.
Console.WriteLine($"Created On : {operation.CreatedOn}");
Console.WriteLine($"Expires On : {operation.ExpiresOn}");
Console.WriteLine($"Id : {operation.Id}");
Console.WriteLine($"Status : {operation.Status}");
Console.WriteLine($"Last Modified: {operation.LastModified}");
Console.WriteLine();
// View the operation results.
await foreach (AnalyzeHealthcareEntitiesResultCollection documentsInPage in operation.Value)
{
Console.WriteLine($"Analyze Healthcare Entities, model version: \"{documentsInPage.ModelVersion}\"");
Console.WriteLine();
foreach (AnalyzeHealthcareEntitiesResult documentResult in documentsInPage)
{
if (documentResult.HasError)
{
Console.WriteLine($" Error!");
Console.WriteLine($" Document error code: {documentResult.Error.ErrorCode}");
Console.WriteLine($" Message: {documentResult.Error.Message}");
continue;
}
Console.WriteLine($" Recognized the following {documentResult.Entities.Count} healthcare entities:");
Console.WriteLine();
// View the healthcare entities that were recognized.
foreach (HealthcareEntity entity in documentResult.Entities)
{
Console.WriteLine($" Entity: {entity.Text}");
Console.WriteLine($" Category: {entity.Category}");
Console.WriteLine($" Offset: {entity.Offset}");
Console.WriteLine($" Length: {entity.Length}");
Console.WriteLine($" NormalizedText: {entity.NormalizedText}");
Console.WriteLine($" Links:");
// View the entity data sources.
foreach (EntityDataSource entityDataSource in entity.DataSources)
{
Console.WriteLine($" Entity ID in Data Source: {entityDataSource.EntityId}");
Console.WriteLine($" DataSource: {entityDataSource.Name}");
}
// View the entity assertions.
if (entity.Assertion is not null)
{
Console.WriteLine($" Assertions:");
if (entity.Assertion?.Association is not null)
{
Console.WriteLine($" Association: {entity.Assertion?.Association}");
}
if (entity.Assertion?.Certainty is not null)
{
Console.WriteLine($" Certainty: {entity.Assertion?.Certainty}");
}
if (entity.Assertion?.Conditionality is not null)
{
Console.WriteLine($" Conditionality: {entity.Assertion?.Conditionality}");
}
}
}
Console.WriteLine($" We found {documentResult.EntityRelations.Count} relations in the current document:");
Console.WriteLine();
// View the healthcare entity relations that were recognized.
foreach (HealthcareEntityRelation relation in documentResult.EntityRelations)
{
Console.WriteLine($" Relation: {relation.RelationType}");
if (relation.ConfidenceScore is not null)
{
Console.WriteLine($" ConfidenceScore: {relation.ConfidenceScore}");
}
Console.WriteLine($" For this relation there are {relation.Roles.Count} roles");
// View the relation roles.
foreach (HealthcareEntityRelationRole role in relation.Roles)
{
Console.WriteLine($" Role Name: {role.Name}");
Console.WriteLine($" Associated Entity Text: {role.Entity.Text}");
Console.WriteLine($" Associated Entity Category: {role.Entity.Category}");
Console.WriteLine();
}
Console.WriteLine();
}
Console.WriteLine();
}
}
异步运行多个动作
此功能允许在一份或更多文档中运行多个操作。操作包括:
- 命名实体识别
- PII实体识别
- 链接实体识别
- 关键短语提取
- 情感分析
- 医疗实体识别(请参阅此处的示例)
- 自定义命名实体识别(请参阅此处的示例)
- 自定义单标签分类(请参阅此处的示例)
- 自定义多标签分类(请参阅此处的示例)
string documentA =
"We love this trail and make the trip every year. The views are breathtaking and well worth the hike!"
+ " Yesterday was foggy though, so we missed the spectacular views. We tried again today and it was"
+ " amazing. Everyone in my family liked the trail although it was too challenging for the less"
+ " athletic among us.";
string documentB =
"Last week we stayed at Hotel Foo to celebrate our anniversary. The staff knew about our anniversary"
+ " so they helped me organize a little surprise for my partner. The room was clean and with the"
+ " decoration I requested. It was perfect!";
// Prepare the input of the text analysis operation. You can add multiple documents to this list and
// perform the same operation on all of them simultaneously.
List<string> batchedDocuments = new()
{
documentA,
documentB
};
TextAnalyticsActions actions = new()
{
ExtractKeyPhrasesActions = new List<ExtractKeyPhrasesAction>() { new ExtractKeyPhrasesAction() { ActionName = "ExtractKeyPhrasesSample" } },
RecognizeEntitiesActions = new List<RecognizeEntitiesAction>() { new RecognizeEntitiesAction() { ActionName = "RecognizeEntitiesSample" } },
DisplayName = "AnalyzeOperationSample"
};
// Perform the text analysis operation.
AnalyzeActionsOperation operation = await client.AnalyzeActionsAsync(WaitUntil.Completed, batchedDocuments, actions);
// View the operation status.
Console.WriteLine($"Created On : {operation.CreatedOn}");
Console.WriteLine($"Expires On : {operation.ExpiresOn}");
Console.WriteLine($"Id : {operation.Id}");
Console.WriteLine($"Status : {operation.Status}");
Console.WriteLine($"Last Modified: {operation.LastModified}");
Console.WriteLine();
if (!string.IsNullOrEmpty(operation.DisplayName))
{
Console.WriteLine($"Display name: {operation.DisplayName}");
Console.WriteLine();
}
Console.WriteLine($"Total actions: {operation.ActionsTotal}");
Console.WriteLine($" Succeeded actions: {operation.ActionsSucceeded}");
Console.WriteLine($" Failed actions: {operation.ActionsFailed}");
Console.WriteLine($" In progress actions: {operation.ActionsInProgress}");
Console.WriteLine();
await foreach (AnalyzeActionsResult documentsInPage in operation.Value)
{
IReadOnlyCollection<ExtractKeyPhrasesActionResult> keyPhrasesResults = documentsInPage.ExtractKeyPhrasesResults;
IReadOnlyCollection<RecognizeEntitiesActionResult> entitiesResults = documentsInPage.RecognizeEntitiesResults;
Console.WriteLine("Recognized Entities");
int docNumber = 1;
foreach (RecognizeEntitiesActionResult entitiesActionResults in entitiesResults)
{
Console.WriteLine($" Action name: {entitiesActionResults.ActionName}");
Console.WriteLine();
foreach (RecognizeEntitiesResult documentResult in entitiesActionResults.DocumentsResults)
{
Console.WriteLine($" Document #{docNumber++}");
Console.WriteLine($" Recognized {documentResult.Entities.Count} entities:");
foreach (CategorizedEntity entity in documentResult.Entities)
{
Console.WriteLine();
Console.WriteLine($" Entity: {entity.Text}");
Console.WriteLine($" Category: {entity.Category}");
Console.WriteLine($" Offset: {entity.Offset}");
Console.WriteLine($" Length: {entity.Length}");
Console.WriteLine($" ConfidenceScore: {entity.ConfidenceScore}");
Console.WriteLine($" SubCategory: {entity.SubCategory}");
}
Console.WriteLine();
}
}
Console.WriteLine("Extracted Key Phrases");
docNumber = 1;
foreach (ExtractKeyPhrasesActionResult keyPhrasesActionResult in keyPhrasesResults)
{
Console.WriteLine($" Action name: {keyPhrasesActionResult.ActionName}");
Console.WriteLine();
foreach (ExtractKeyPhrasesResult documentResults in keyPhrasesActionResult.DocumentsResults)
{
Console.WriteLine($" Document #{docNumber++}");
Console.WriteLine($" Recognized the following {documentResults.KeyPhrases.Count} Keyphrases:");
foreach (string keyphrase in documentResults.KeyPhrases)
{
Console.WriteLine($" {keyphrase}");
}
Console.WriteLine();
}
}
}
}
故障排除
通用
当您使用.NET文本分析SDK与语言认知服务交互时,语言服务返回的错误与REST API请求返回的相同HTTP状态代码。
例如,如果您提交包含重复文档ID的文本文档输入批次,将返回一个400错误,指示“无效请求”。
try
{
DetectedLanguage result = client.DetectLanguage(document);
}
catch (RequestFailedException e)
{
Console.WriteLine(e.ToString());
}
您将注意到还记录了其他信息,例如操作的操作客户端请求ID。
Message:
Azure.RequestFailedException:
Status: 400 (Bad Request)
Content:
{"error":{"code":"InvalidRequest","innerError":{"code":"InvalidDocument","message":"Request contains duplicated Ids. Make sure each document has a unique Id."},"message":"Invalid document in request."}}
Headers:
Transfer-Encoding: chunked
x-aml-ta-request-id: 146ca04a-af54-43d4-9872-01a004bee5f8
X-Content-Type-Options: nosniff
x-envoy-upstream-service-time: 6
apim-request-id: c650acda-2b59-4ff7-b96a-e316442ea01b
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
Date: Wed, 18 Dec 2019 16:24:52 GMT
Content-Type: application/json; charset=utf-8
设置控制台日志记录
查看日志最简单的方法是启用控制台日志记录。要创建将消息输出到控制台的自定义日志监听器,请使用AzureEventSourceListener.CreateConsoleLogger方法。
// Setup a listener to monitor logged events.
using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger();
有关其他日志记录机制的更多信息,请参阅此处。
下一步
本GitHub仓库中提供了使用此客户端库的示例。每个主要功能区域都有示例,在各个区域中,提供了分析单个文档和在进行同步和异步模式下的文档集合的示例。
高级示例
贡献
有关构建、测试和为此库作出贡献的详细信息,请参阅CONTRIBUTING.md。
该项目欢迎贡献和建议。大多数贡献都需要您同意贡献者许可协议(CLA),声明您有权并且实际上确实赋予我们使用您贡献的权利。有关详细信息,请访问cla.microsoft.com。
提交拉取请求时,CLA-bot将自动确定您是否需要提供CLA,并适当标记PR(例如,标签、评论)。只需遵循bot提供的说明。您只需在整个使用我们CLA的所有仓库中这样做一次。
本项目已采用Microsoft开源行为准则。更多信息请参阅行为准则常见问题或联系opencode@microsoft.com以索取其他问题或注释。
| 产品 | 版本 兼容和额外的计算目标框架版本。 |
|---|---|
| .NET | net5.0 已计算。 net5.0-windows 已计算。 net6.0 已计算。 net6.0-android 已计算。 net6.0-ios 已计算。 net6.0-maccatalyst 已计算。 net6.0-macos 已计算。 net6.0-tvos 已计算。 net6.0-windows 已计算。 net7.0 已计算。 net7.0-android 已计算。 net7.0-ios 已计算。 net7.0-maccatalyst 已计算。 net7.0-macos 已计算。 net7.0-tvos 已计算。 net7.0-windows 已计算。 net8.0 已计算。 net8.0-android 已计算。 net8.0-browser 已计算。 net8.0-ios 已计算。 net8.0-maccatalyst 已计算。 net8.0-macos 已计算。 net8.0-tvos 已计算。 net8.0-windows 已计算。 |
| NET Core | netcoreapp2.0 已计算。 netcoreapp2.1 已计算。 netcoreapp2.2 已计算。 netcoreapp3.0 已计算。 netcoreapp3.1 已计算。 |
| NET Standard | netstandard2.0 兼容。 netstandard2.1 已计算。 |
| NET Framework | net461 已计算。 net462 已计算。 net463 已计算。 net47 已计算。 net471 已计算。 net472 已计算。 net48 已计算。 net481 已计算。 |
| MonoAndroid | monoandroid 已计算。 |
| MonoMac | monomac 已计算。 |
| MonoTouch | monotouch 已计算。 |
| Tizen | tizen40 已计算。 tizen60 已计算。 |
| Xamarin.iOS | xamarinios 已计算。 |
| Xamarin.Mac | xamarinmac 已计算。 |
| Xamarin.TVOS | xamarintvos 已计算。 |
| Xamarin.WatchOS | xamarinwatchos 已计算。 |
-
.NETStandard 2.0
- Azure.Core (>= 1.33.0)
- Microsoft.Bcl.AsyncInterfaces (>= 1.1.1)
- System.Text.Json (>= 4.7.2)
NuGet包 (9)
显示依赖 Azure.AI.TextAnalytics 的前 5 个 NuGet 包
| 包 | 下载 |
|---|---|
|
Kentico.Xperience.Libraries 使用 Kentico Xperience API 的库和应用程序的运行时程序集。 |
|
|
GoodToCode.Shared.TextAnalytics.CognitiveServices
GoodToCode 共享面向方面(AOP)库,用于跨领域实用程序关注点。 |
|
|
Encamina.Enmarcha.AI.LanguagesDetection.Azure
包描述 |
|
|
AICentral.Logging.PIIStripping
包描述 |
|
|
NLPService
包描述 |
GitHub 存储库 (7)
显示依赖 Azure.AI.TextAnalytics 的前 5 个最受欢迎的 GitHub 存储库
| 存储库 | 星标 |
|---|---|
|
Azure-Samples/cognitive-services-speech-sdk
Microsoft Cognitive Services Speech SDK 的示例代码
|
|
|
microsoft/Cognitive-Samples-IntelligentKiosk
欢迎访问智能信息亭样本!在这里,您将找到一些演示,展示了构建在 Microsoft Cognitive Services 之上的工作流程和体验。
|
|
|
jamesmontemagno/Hanselman.Forms
最酷的 Hanselman 应用
|
|
|
Azure-Samples/azure-search-power-skills
集合了一些有用的函数,可部署为 Azure 认知搜索的自定义技能
|
|
|
brminnick/HackerNews
一个.NET MAUI应用程序,用于显示Hacker News上的热门帖子,展示了使用人工智能收集的文本情感分析
|
| 版本 | 下载 | 上次更新 |
|---|---|---|
| 5.3.0 | 600,024 | 6/20/2023 |
| 5.3.0-beta.3 | 51,261 | 3/13/2023 |
| 5.3.0-beta.2 | 1,426 | 3/8/2023 |
| 5.3.0-beta.1 | 21,348 | 12/1/2022 |
| 5.2.0 | 531,447 | 9/9/2022 |
| 5.2.0-beta.4 | 1,041 | 8/12/2022 |
| 5.2.0-beta.3 | 14,012 | 5/18/2022 |
| 5.2.0-beta.2 | 14,723 | 11/2/2021 |
| 5.2.0-beta.1 | 16,848 | 8/9/2021 |
| 5.1.1 | 370,558 | 11/19/2021 |
| 5.1.0 | 163,032 | 7/7/2021 |
| 5.0.0 | 702,370 | 7/28/2020 |
| 1.0.1 | 26,494 | 6/23/2020 |
| 1.0.0 | 17,222 | 6/9/2020 |