你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

TextAnalyticsClient 类

语言服务 API 是一套使用一流的 Microsoft 机器学习算法构建的自然语言处理 (NLP) 技能。 API 可用于分析情绪分析、关键短语提取、实体识别和语言检测等任务的非结构化文本。

可在 https://docs.microsoft.com/azure/cognitive-services/language-service/overview

继承
azure.ai.textanalytics._base_client.TextAnalyticsClientBase
TextAnalyticsClient

构造函数

TextAnalyticsClient(endpoint: str, credential: AzureKeyCredential | TokenCredential, *, default_language: str | None = None, default_country_hint: str | None = None, api_version: str | TextAnalyticsApiVersion | None = None, **kwargs: Any)

参数

endpoint
str
必需

支持的认知服务或语言资源终结点 (协议和主机名,例如:“https://.cognitiveservices.azure.com”) 。

credential
AzureKeyCredentialTokenCredential
必需

客户端连接到 Azure 所需的凭据。 如果使用认知服务/语言 API 密钥或中的 identity令牌凭据,则这可以是 AzureKeyCredential 的实例。

default_country_hint
str

设置用于所有操作的默认country_hint。 默认为“US”。 如果不想使用国家/地区提示,请传递字符串“none”。

default_language
str

设置用于所有操作的默认语言。 默认为“en”。

api_version
strTextAnalyticsApiVersion

要用于请求的服务的 API 版本。 它默认为最新的服务版本。 设置为较旧版本可能会导致功能兼容性降低。

示例

使用终结点和 API 密钥创建 TextAnalyticsClient。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient
   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint, AzureKeyCredential(key))

使用 Azure Active Directory 中的终结点和令牌凭据创建 TextAnalyticsClient。


   import os
   from azure.ai.textanalytics import TextAnalyticsClient
   from azure.identity import DefaultAzureCredential

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   credential = DefaultAzureCredential()

   text_analytics_client = TextAnalyticsClient(endpoint, credential=credential)

方法

analyze_sentiment

分析一批文档的情绪。 使用 show_opinion_mining启用观点挖掘。

返回情绪预测,以及文档及其中的每个句子 (正面、负面和中性) 每个情绪类的情绪分数。

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能:show_opinion_miningdisable_service_logsstring_index_type关键字 (keyword) 参数。

begin_abstract_summary

启动长时间运行的抽象摘要操作。

有关抽象摘要的概念性讨论,请参阅服务文档: https://video2.skills-academy.com/azure/cognitive-services/language-service/summarization/overview

版本 2023-04-01 中的新增功能: begin_abstract_summary 客户端方法。

begin_analyze_actions

启动长时间运行的操作,对一批文档执行各种文本分析操作。

如果要分析较大的文档和/或将多个文本分析操作合并到一个调用中,建议使用此函数。 否则,建议使用特定于操作的终结点,例如 analyze_sentiment

注意

有关自定义操作功能的区域支持,请参阅服务文档:

https://aka.ms/azsdk/textanalytics/customfunctionalities

版本 v3.1 中的新增功能: begin_analyze_actions 客户端方法。

版本 2022-05-01 中的新增功能: RecognizeCustomEntitiesActionSingleLabelClassifyActionMultiLabelClassifyActionAnalyzeHealthcareEntitiesAction 输入选项以及相应的 RecognizeCustomEntitiesResultClassifyDocumentResultAnalyzeHealthcareEntitiesResult 结果对象

版本 2023-04-01 中的新增功能: ExtractiveSummaryActionAbstractiveSummaryAction 输入选项以及相应的 ExtractiveSummaryResultAbstractiveSummaryResult 结果对象。

begin_analyze_healthcare_entities

分析医疗保健实体,并在一批文档中识别这些实体之间的关系。

实体与可在现有知识库(如 UMLS、CHV、MSH 等)中找到的引用相关联。

我们还提取实体之间的关系,例如在“受试者服用100毫克布洛芬”中,我们将提取“100毫克”剂量与“布洛芬”药物之间的关系。

版本 v3.1 中的新增功能: begin_analyze_healthcare_entities 客户端方法。

版本 2022-05-01 中的新增功能:display_name 关键字 (keyword) 参数。

begin_extract_summary

启动长时间运行的提取式汇总操作。

有关提取式摘要的概念性讨论,请参阅服务文档: https://video2.skills-academy.com/azure/cognitive-services/language-service/summarization/overview

版本 2023-04-01 中的新增功能: begin_extract_summary 客户端方法。

begin_multi_label_classify

启动长时间运行的自定义多标签分类操作。

有关自定义功能的区域支持以及如何训练模型以对文档进行分类的信息,请参阅 https://aka.ms/azsdk/textanalytics/customfunctionalities

版本 2022-05-01 中的新增功能: begin_multi_label_classify 客户端方法。

begin_recognize_custom_entities

启动长时间运行的自定义命名实体识别操作。

有关自定义功能的区域支持以及如何训练模型以识别自定义实体的信息,请参阅 https://aka.ms/azsdk/textanalytics/customentityrecognition

版本 2022-05-01 中的新增功能: begin_recognize_custom_entities 客户端方法。

begin_single_label_classify

启动长时间运行的自定义单标签分类操作。

有关自定义功能的区域支持以及如何训练模型以对文档进行分类的信息,请参阅 https://aka.ms/azsdk/textanalytics/customfunctionalities

版本 2022-05-01 中的新增功能: begin_single_label_classify 客户端方法。

close

关闭客户端打开的套接字。 使用客户端作为上下文管理器时,不需要调用此方法。

detect_language

检测一批文档的语言。

返回检测到的语言和介于零和 1 之间的数字分数。 分数接近 1 表示 100% 确定所标识的语言是正确的。 有关已启用的语言列表,请参阅 https://aka.ms/talangs

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能:disable_service_logs 关键字 (keyword) 参数。

extract_key_phrases

从一批文档中提取关键短语。

返回表示输入文本中关键短语的字符串列表。 例如,对于输入文本“食物很美味,有出色的工作人员”,API 返回main谈话点:“食物”和“美妙的员工”

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能:disable_service_logs 关键字 (keyword) 参数。

recognize_entities

识别一批文档的实体。

识别文本中的实体并将其分类为人员、地点、组织、日期/时间、数量、百分比、货币等。 有关支持的实体类型的列表,检查:https://aka.ms/taner

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能:disable_service_logsstring_index_type关键字 (keyword) 参数。

recognize_linked_entities

从已知知识库识别一批文档的链接实体。

识别和消除文本 (中的每个实体的身份,例如,确定“火星”一词的出现是指行星,还是罗马战神) 。 识别的实体与已知知识库(如维基百科)的 URL 相关联。

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能:disable_service_logsstring_index_type关键字 (keyword) 参数。

recognize_pii_entities

识别包含一批文档的个人信息的实体。

返回文档中) (“SSN”、“银行帐户”等个人信息实体的列表。 有关支持的实体类型的列表,检查 https://aka.ms/azsdk/language/pii

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能: recognize_pii_entities 客户端方法。

analyze_sentiment

分析一批文档的情绪。 使用 show_opinion_mining启用观点挖掘。

返回情绪预测,以及文档及其中的每个句子 (正面、负面和中性) 每个情绪类的情绪分数。

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能:show_opinion_miningdisable_service_logsstring_index_type关键字 (keyword) 参数。

analyze_sentiment(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, disable_service_logs: bool | None = None, language: str | None = None, model_version: str | None = None, show_opinion_mining: bool | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> List[AnalyzeSentimentResult | DocumentError]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项目指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

show_opinion_mining
bool

是否挖掘句子的意见,并围绕产品或服务的各个方面进行更精细的分析 (也称为基于方面的情绪分析) 。 如果设置为 true,则返回 SentenceSentiment 的对象将具有包含此分析结果 的属性mined_opinions 。 仅适用于 API 版本 v3.1 及版本版本。

language
str

整个批次语言的 2 个字母 ISO 639-1 表示形式。 例如,对英语使用“en”;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

model_version
str

用于分析的模型版本,例如“latest”。 如果未指定模型版本,API 将默认为最新的非预览版本。 有关详细信息,请参阅此处: https://aka.ms/text-analytics-model-versioning

show_stats
bool

如果设置为 true,则响应将在文档级响应的 统计信息 字段中包含文档级统计信息。

string_index_type
str

指定用于解释字符串偏移量的方法。 UnicodeCodePoint 是默认的 Python 编码。 若要替代 Python 默认值,还可以传入 Utf16CodeUnitTextElement_v8。 有关其他信息,请参阅 https://aka.ms/text-analytics-offsets

disable_service_logs
bool

如果设置为 true,则选择退出在服务端记录文本输入进行故障排除。 默认情况下,语言服务会记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 将此参数设置为 true 会禁用输入日志记录,并可能限制我们修正出现的问题的能力。 有关详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及 Microsoft https://www.microsoft.com/ai/responsible-ai负责任 AI 原则。

返回

DocumentError 的组合列表AnalyzeSentimentResult,按原始文档的传递顺序排列。

返回类型

例外

示例

分析一批文档中的情绪。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

   documents = [
       """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.""",
       """This was a waste of my time. All of the views on this drop are extremely boring, all I saw was grass. 0/10 would
       not recommend to any divers, even first timers.""",
       """This was pretty good! The sights were ok, and I had fun with my instructors! Can't complain too much about my experience""",
       """I only have one word for my experience: WOW!!! I can't believe I have had such a wonderful skydiving company right
       in my backyard this whole time! I will definitely be a repeat customer, and I want to take my grandmother skydiving too,
       I know she'll love it!"""
   ]


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

   print("Let's visualize the sentiment of each of these documents")
   for idx, doc in enumerate(docs):
       print(f"Document text: {documents[idx]}")
       print(f"Overall sentiment: {doc.sentiment}")

begin_abstract_summary

启动长时间运行的抽象摘要操作。

有关抽象摘要的概念性讨论,请参阅服务文档: https://video2.skills-academy.com/azure/cognitive-services/language-service/summarization/overview

版本 2023-04-01 中的新增功能: begin_abstract_summary 客户端方法。

begin_abstract_summary(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, model_version: str | None = None, string_index_type: str | None = None, sentence_count: int | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[AbstractiveSummaryResult | DocumentError]]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项目指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

language
str

整个批次语言的 2 个字母 ISO 639-1 表示形式。 例如,对英语使用“en”;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

show_stats
bool

如果设置为 true,则响应将包含文档级别统计信息。

sentence_count
Optional[int]

它控制输出摘要中的大致句子数。

model_version
Optional[str]

用于分析的模型版本,例如“latest”。 如果未指定模型版本,API 将默认为最新的非预览版本。 有关详细信息,请参阅此处: https://aka.ms/text-analytics-model-versioning

string_index_type
Optional[str]

指定用于解释字符串偏移量的方法。

disable_service_logs
bool

如果设置为 true,则选择退出在服务端记录文本输入进行故障排除。 默认情况下,语言服务会记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 将此参数设置为 true 会禁用输入日志记录,并可能限制我们修正出现的问题的能力。 有关详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及 Microsoft https://www.microsoft.com/ai/responsible-ai负责任 AI 原则。

polling_interval
int

如果没有 Retry-After 标头,则 LRO 操作的两次轮询之间的等待时间。 默认为 5 秒。

continuation_token
str

对轮询器对象调用 continuation_token () ,将长时间运行的操作 (LRO) 状态保存到不透明的令牌中。 将值作为continuation_token关键字 (keyword) 参数传递,以从保存状态重启 LRO。

display_name
str

要为请求的分析设置的可选显示名称。

返回

TextAnalysisLROPoller 的实例。 在此对象上调用 result () 以返回 和 DocumentErrorAbstractiveSummaryResult异类分页。

返回类型

例外

示例

对一批文档执行抽象摘要。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   document = [
       "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic, "
       "human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI Cognitive "
       "Services, I have been working with a team of amazing scientists and engineers to turn this quest into a "
       "reality. In my role, I enjoy a unique perspective in viewing the relationship among three attributes of "
       "human cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z). At the "
       "intersection of all three, there's magic-what we call XYZ-code as illustrated in Figure 1-a joint "
       "representation to create more powerful AI that can speak, hear, see, and understand humans better. "
       "We believe XYZ-code will enable us to fulfill our long-term vision: cross-domain transfer learning, "
       "spanning modalities and languages. The goal is to have pretrained models that can jointly learn "
       "representations to support a broad range of downstream AI tasks, much in the way humans do today. "
       "Over the past five years, we have achieved human performance on benchmarks in conversational speech "
       "recognition, machine translation, conversational question answering, machine reading comprehension, "
       "and image captioning. These five breakthroughs provided us with strong signals toward our more ambitious "
       "aspiration to produce a leap in AI capabilities, achieving multisensory and multilingual learning that "
       "is closer in line with how humans learn and understand. I believe the joint XYZ-code is a foundational "
       "component of this aspiration, if grounded with external knowledge sources in the downstream AI tasks."
   ]

   poller = text_analytics_client.begin_abstract_summary(document)
   abstract_summary_results = poller.result()
   for result in abstract_summary_results:
       if result.kind == "AbstractiveSummarization":
           print("Summaries abstracted:")
           [print(f"{summary.text}\n") for summary in result.summaries]
       elif result.is_error is True:
           print("...Is an error with code '{}' and message '{}'".format(
               result.error.code, result.error.message
           ))

begin_analyze_actions

启动长时间运行的操作,对一批文档执行各种文本分析操作。

如果要分析较大的文档和/或将多个文本分析操作合并到一个调用中,建议使用此函数。 否则,建议使用特定于操作的终结点,例如 analyze_sentiment

注意

有关自定义操作功能的区域支持,请参阅服务文档:

https://aka.ms/azsdk/textanalytics/customfunctionalities

版本 v3.1 中的新增功能: begin_analyze_actions 客户端方法。

版本 2022-05-01 中的新增功能: RecognizeCustomEntitiesActionSingleLabelClassifyActionMultiLabelClassifyActionAnalyzeHealthcareEntitiesAction 输入选项以及相应的 RecognizeCustomEntitiesResultClassifyDocumentResultAnalyzeHealthcareEntitiesResult 结果对象

版本 2023-04-01 中的新增功能: ExtractiveSummaryActionAbstractiveSummaryAction 输入选项以及相应的 ExtractiveSummaryResultAbstractiveSummaryResult 结果对象。

begin_analyze_actions(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], actions: List[RecognizeEntitiesAction | RecognizeLinkedEntitiesAction | RecognizePiiEntitiesAction | ExtractKeyPhrasesAction | AnalyzeSentimentAction | RecognizeCustomEntitiesAction | SingleLabelClassifyAction | MultiLabelClassifyAction | AnalyzeHealthcareEntitiesAction | ExtractiveSummaryAction | AbstractiveSummaryAction], *, continuation_token: str | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[List[RecognizeEntitiesResult | RecognizeLinkedEntitiesResult | RecognizePiiEntitiesResult | ExtractKeyPhrasesResult | AnalyzeSentimentResult | RecognizeCustomEntitiesResult | ClassifyDocumentResult | AnalyzeHealthcareEntitiesResult | ExtractiveSummaryResult | AbstractiveSummaryResult | DocumentError]]]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项目指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

actions
list[RecognizeEntitiesActionRecognizePiiEntitiesActionExtractKeyPhrasesActionRecognizeLinkedEntitiesActionAnalyzeSentimentActionRecognizeCustomEntitiesActionSingleLabelClassifyActionMultiLabelClassifyActionAnalyzeHealthcareEntitiesActionExtractiveSummaryActionAbstractiveSummaryAction]
必需

要对输入文档执行的操作的异类列表。 每个操作对象封装用于特定操作类型的参数。 操作结果与输入操作的顺序相同。

display_name
str

要为请求的分析设置的可选显示名称。

language
str

整个批次语言的 2 个字母 ISO 639-1 表示形式。 例如,对英语使用“en”;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

show_stats
bool

如果设置为 true,则响应将包含文档级别统计信息。

polling_interval
int

如果没有 Retry-After 标头,则 LRO 操作的两次轮询之间的等待时间。 默认为 5 秒。

continuation_token
str

对轮询器对象调用 continuation_token () ,将长时间运行的操作 (LRO) 状态保存到不透明的令牌中。 将值作为continuation_token关键字 (keyword) 参数传递,以从保存状态重启 LRO。

返回

TextAnalysisLROPoller 的实例。 对轮询器对象调用 result () 以返回可分页的异类列表列表。 此列表列表首先按输入的文档排序,然后按输入的操作排序。 例如,如果有文档输入 [“Hello”, “world”] 和 操作 RecognizeEntitiesActionAnalyzeSentimentAction在循环访问列表时,将首先循环访问“Hello”文档的操作结果,然后获取“Hello”,然后AnalyzeSentimentResult获取RecognizeEntitiesResult“Hello”的 。 然后,你将得到 RecognizeEntitiesResult “world”的 和 AnalyzeSentimentResult

返回类型

例外

示例

启动长时间运行的操作,对一批文档执行各种文本分析操作。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import (
       TextAnalyticsClient,
       RecognizeEntitiesAction,
       RecognizeLinkedEntitiesAction,
       RecognizePiiEntitiesAction,
       ExtractKeyPhrasesAction,
       AnalyzeSentimentAction,
   )

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   documents = [
       'We went to Contoso Steakhouse located at midtown NYC last week for a dinner party, and we adore the spot! '
       'They provide marvelous food and they have a great menu. The chief cook happens to be the owner (I think his name is John Doe) '
       'and he is super nice, coming out of the kitchen and greeted us all.'
       ,

       'We enjoyed very much dining in the place! '
       'The Sirloin steak I ordered was tender and juicy, and the place was impeccably clean. You can even pre-order from their '
       'online menu at www.contososteakhouse.com, call 312-555-0176 or send email to order@contososteakhouse.com! '
       'The only complaint I have is the food didn\'t come fast enough. Overall I highly recommend it!'
   ]

   poller = text_analytics_client.begin_analyze_actions(
       documents,
       display_name="Sample Text Analysis",
       actions=[
           RecognizeEntitiesAction(),
           RecognizePiiEntitiesAction(),
           ExtractKeyPhrasesAction(),
           RecognizeLinkedEntitiesAction(),
           AnalyzeSentimentAction(),
       ],
   )

   document_results = poller.result()
   for doc, action_results in zip(documents, document_results):
       print(f"\nDocument text: {doc}")
       for result in action_results:
           if result.kind == "EntityRecognition":
               print("...Results of Recognize Entities Action:")
               for entity in result.entities:
                   print(f"......Entity: {entity.text}")
                   print(f".........Category: {entity.category}")
                   print(f".........Confidence Score: {entity.confidence_score}")
                   print(f".........Offset: {entity.offset}")

           elif result.kind == "PiiEntityRecognition":
               print("...Results of Recognize PII Entities action:")
               for pii_entity in result.entities:
                   print(f"......Entity: {pii_entity.text}")
                   print(f".........Category: {pii_entity.category}")
                   print(f".........Confidence Score: {pii_entity.confidence_score}")

           elif result.kind == "KeyPhraseExtraction":
               print("...Results of Extract Key Phrases action:")
               print(f"......Key Phrases: {result.key_phrases}")

           elif result.kind == "EntityLinking":
               print("...Results of Recognize Linked Entities action:")
               for linked_entity in result.entities:
                   print(f"......Entity name: {linked_entity.name}")
                   print(f".........Data source: {linked_entity.data_source}")
                   print(f".........Data source language: {linked_entity.language}")
                   print(
                       f".........Data source entity ID: {linked_entity.data_source_entity_id}"
                   )
                   print(f".........Data source URL: {linked_entity.url}")
                   print(".........Document matches:")
                   for match in linked_entity.matches:
                       print(f"............Match text: {match.text}")
                       print(f"............Confidence Score: {match.confidence_score}")
                       print(f"............Offset: {match.offset}")
                       print(f"............Length: {match.length}")

           elif result.kind == "SentimentAnalysis":
               print("...Results of Analyze Sentiment action:")
               print(f"......Overall sentiment: {result.sentiment}")
               print(
                   f"......Scores: positive={result.confidence_scores.positive}; \
                   neutral={result.confidence_scores.neutral}; \
                   negative={result.confidence_scores.negative} \n"
               )

           elif result.is_error is True:
               print(
                   f"...Is an error with code '{result.error.code}' and message '{result.error.message}'"
               )

       print("------------------------------------------")


begin_analyze_healthcare_entities

分析医疗保健实体,并在一批文档中识别这些实体之间的关系。

实体与可在现有知识库(如 UMLS、CHV、MSH 等)中找到的引用相关联。

我们还提取实体之间的关系,例如在“受试者服用100毫克布洛芬”中,我们将提取“100毫克”剂量与“布洛芬”药物之间的关系。

版本 v3.1 中的新增功能: begin_analyze_healthcare_entities 客户端方法。

版本 2022-05-01 中的新增功能:display_name 关键字 (keyword) 参数。

begin_analyze_healthcare_entities(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, model_version: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> AnalyzeHealthcareEntitiesLROPoller[ItemPaged[AnalyzeHealthcareEntitiesResult | DocumentError]]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式的 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

model_version
str

用于分析的模型版本,例如“latest”。 如果未指定模型版本,API 将默认为最新的非预览版本。 有关详细信息,请参阅此处: https://aka.ms/text-analytics-model-versioning

show_stats
bool

如果设置为 true,则响应将包含文档级统计信息。

language
str

整个批语言的 2 个字母 ISO 639-1 表示形式。 例如,将“en”用于英语;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

display_name
str

要为请求的分析设置的可选显示名称。

string_index_type
str

指定用于解释字符串偏移量的方法。 UnicodeCodePoint 是默认的 Python 编码。 若要替代 Python 默认值,还可以传入 Utf16CodeUnitTextElement_v8。 有关其他信息,请参阅 https://aka.ms/text-analytics-offsets

polling_interval
int

如果没有 Retry-After 标头,则 LRO 操作的两次轮询之间的等待时间。 默认为 5 秒。

continuation_token
str

对轮询器对象调用 continuation_token () ,将长时间运行的操作 (LRO) 状态保存到不透明令牌中。 将值作为continuation_token关键字 (keyword) 参数传递,以从保存状态重启 LRO。

disable_service_logs
bool

默认为 true,这意味着语言服务不会在服务端记录输入文本以便进行故障排除。 如果设置为 False,则语言服务将记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 有关更多详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及上的 https://www.microsoft.com/ai/responsible-aiMicrosoft 负责任 AI 原则。

返回

AnalyzeHealthcareEntitiesLROPoller 的实例。 在此对象上调用 result () 以返回 和 DocumentErrorAnalyzeHealthcareEntitiesResult异类分页。

返回类型

例外

示例

识别一批文档中的医疗保健实体。


   import os
   import typing
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient, HealthcareEntityRelation

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   documents = [
       """
       Patient needs to take 100 mg of ibuprofen, and 3 mg of potassium. Also needs to take
       10 mg of Zocor.
       """,
       """
       Patient needs to take 50 mg of ibuprofen, and 2 mg of Coumadin.
       """
   ]

   poller = text_analytics_client.begin_analyze_healthcare_entities(documents)
   result = poller.result()

   docs = [doc for doc in result if not doc.is_error]

   print("Let's first visualize the outputted healthcare result:")
   for doc in docs:
       for entity in doc.entities:
           print(f"Entity: {entity.text}")
           print(f"...Normalized Text: {entity.normalized_text}")
           print(f"...Category: {entity.category}")
           print(f"...Subcategory: {entity.subcategory}")
           print(f"...Offset: {entity.offset}")
           print(f"...Confidence score: {entity.confidence_score}")
           if entity.data_sources is not None:
               print("...Data Sources:")
               for data_source in entity.data_sources:
                   print(f"......Entity ID: {data_source.entity_id}")
                   print(f"......Name: {data_source.name}")
           if entity.assertion is not None:
               print("...Assertion:")
               print(f"......Conditionality: {entity.assertion.conditionality}")
               print(f"......Certainty: {entity.assertion.certainty}")
               print(f"......Association: {entity.assertion.association}")
       for relation in doc.entity_relations:
           print(f"Relation of type: {relation.relation_type} has the following roles")
           for role in relation.roles:
               print(f"...Role '{role.name}' with entity '{role.entity.text}'")
       print("------------------------------------------")

   print("Now, let's get all of medication dosage relations from the documents")
   dosage_of_medication_relations = [
       entity_relation
       for doc in docs
       for entity_relation in doc.entity_relations if entity_relation.relation_type == HealthcareEntityRelation.DOSAGE_OF_MEDICATION
   ]

begin_extract_summary

启动长时间运行的提取式汇总操作。

有关提取式摘要的概念性讨论,请参阅服务文档: https://video2.skills-academy.com/azure/cognitive-services/language-service/summarization/overview

版本 2023-04-01 中的新增功能: begin_extract_summary 客户端方法。

begin_extract_summary(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, model_version: str | None = None, string_index_type: str | None = None, max_sentence_count: int | None = None, order_by: Literal['Rank', 'Offset'] | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[ExtractiveSummaryResult | DocumentError]]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式的 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

language
str

整个批语言的 2 个字母 ISO 639-1 表示形式。 例如,将“en”用于英语;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

show_stats
bool

如果设置为 true,则响应将包含文档级统计信息。

max_sentence_count
Optional[int]

要返回的最大句子数。 默认值为 3。

order_by
Optional[str]

可能的值包括:“Offset”、“Rank”。 默认值:“Offset”。

model_version
Optional[str]

用于分析的模型版本,例如“latest”。 如果未指定模型版本,API 将默认为最新的非预览版本。 有关详细信息,请参阅此处: https://aka.ms/text-analytics-model-versioning

string_index_type
Optional[str]

指定用于解释字符串偏移量的方法。

disable_service_logs
bool

如果设置为 true,则选择不将文本输入记录在服务端进行故障排除。 默认情况下,语言服务会记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 将此参数设置为 true 会禁用输入日志记录,并可能限制我们修正所发生问题的能力。 有关更多详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及上的 https://www.microsoft.com/ai/responsible-aiMicrosoft 负责任 AI 原则。

polling_interval
int

如果没有 Retry-After 标头,则 LRO 操作的两次轮询之间的等待时间。 默认为 5 秒。

continuation_token
str

对轮询器对象调用 continuation_token () ,将长时间运行的操作 (LRO) 状态保存到不透明令牌中。 将值作为continuation_token关键字 (keyword) 参数传递,以从保存状态重启 LRO。

display_name
str

要为请求的分析设置的可选显示名称。

返回

TextAnalysisLROPoller 的实例。 在此对象上调用 result () 以返回 和 DocumentErrorExtractiveSummaryResult异类分页。

返回类型

例外

示例

对一批文档执行提取式摘要。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   document = [
       "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic, "
       "human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI Cognitive "
       "Services, I have been working with a team of amazing scientists and engineers to turn this quest into a "
       "reality. In my role, I enjoy a unique perspective in viewing the relationship among three attributes of "
       "human cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z). At the "
       "intersection of all three, there's magic-what we call XYZ-code as illustrated in Figure 1-a joint "
       "representation to create more powerful AI that can speak, hear, see, and understand humans better. "
       "We believe XYZ-code will enable us to fulfill our long-term vision: cross-domain transfer learning, "
       "spanning modalities and languages. The goal is to have pretrained models that can jointly learn "
       "representations to support a broad range of downstream AI tasks, much in the way humans do today. "
       "Over the past five years, we have achieved human performance on benchmarks in conversational speech "
       "recognition, machine translation, conversational question answering, machine reading comprehension, "
       "and image captioning. These five breakthroughs provided us with strong signals toward our more ambitious "
       "aspiration to produce a leap in AI capabilities, achieving multisensory and multilingual learning that "
       "is closer in line with how humans learn and understand. I believe the joint XYZ-code is a foundational "
       "component of this aspiration, if grounded with external knowledge sources in the downstream AI tasks."
   ]

   poller = text_analytics_client.begin_extract_summary(document)
   extract_summary_results = poller.result()
   for result in extract_summary_results:
       if result.kind == "ExtractiveSummarization":
           print("Summary extracted: \n{}".format(
               " ".join([sentence.text for sentence in result.sentences]))
           )
       elif result.is_error is True:
           print("...Is an error with code '{}' and message '{}'".format(
               result.error.code, result.error.message
           ))

begin_multi_label_classify

启动长时间运行的自定义多标签分类操作。

有关自定义功能的区域支持以及如何训练模型以对文档进行分类的信息,请参阅 https://aka.ms/azsdk/textanalytics/customfunctionalities

版本 2022-05-01 中的新增功能: begin_multi_label_classify 客户端方法。

begin_multi_label_classify(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], project_name: str, deployment_name: str, *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[ClassifyDocumentResult | DocumentError]]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式的 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

project_name
str
必需

必需。 此字段指示模型的项目名称。

deployment_name
str
必需

此字段指示模型的部署名称。

language
str

整个批语言的 2 个字母 ISO 639-1 表示形式。 例如,将“en”用于英语;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

show_stats
bool

如果设置为 true,则响应将包含文档级统计信息。

disable_service_logs
bool

如果设置为 true,则选择不将文本输入记录在服务端进行故障排除。 默认情况下,语言服务会记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 将此参数设置为 true 会禁用输入日志记录,并可能限制我们修正所发生问题的能力。 有关更多详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及上的 https://www.microsoft.com/ai/responsible-aiMicrosoft 负责任 AI 原则。

polling_interval
int

如果没有 Retry-After 标头,则 LRO 操作的两次轮询之间的等待时间。 默认为 5 秒。

continuation_token
str

对轮询器对象调用 continuation_token () ,将长时间运行的操作 (LRO) 状态保存到不透明令牌中。 将值作为continuation_token关键字 (keyword) 参数传递,以从保存状态重启 LRO。

display_name
str

要为请求的分析设置的可选显示名称。

返回

TextAnalysisLROPoller 的实例。 在此对象上调用 result () 以返回 和 DocumentErrorClassifyDocumentResult异类分页。

返回类型

例外

示例

对一批文档执行多标签分类。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]
   project_name = os.environ["MULTI_LABEL_CLASSIFY_PROJECT_NAME"]
   deployment_name = os.environ["MULTI_LABEL_CLASSIFY_DEPLOYMENT_NAME"]
   path_to_sample_document = os.path.abspath(
       os.path.join(
           os.path.abspath(__file__),
           "..",
           "./text_samples/custom_classify_sample.txt",
       )
   )

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   with open(path_to_sample_document) as fd:
       document = [fd.read()]

   poller = text_analytics_client.begin_multi_label_classify(
       document,
       project_name=project_name,
       deployment_name=deployment_name
   )

   document_results = poller.result()
   for doc, classification_result in zip(document, document_results):
       if classification_result.kind == "CustomDocumentClassification":
           classifications = classification_result.classifications
           print(f"\nThe movie plot '{doc}' was classified as the following genres:\n")
           for classification in classifications:
               print("'{}' with confidence score {}.".format(
                   classification.category, classification.confidence_score
               ))
       elif classification_result.is_error is True:
           print("Movie plot '{}' has an error with code '{}' and message '{}'".format(
               doc, classification_result.error.code, classification_result.error.message
           ))

begin_recognize_custom_entities

启动长时间运行的自定义命名实体识别操作。

有关自定义功能的区域支持以及如何训练模型以识别自定义实体的信息,请参阅 https://aka.ms/azsdk/textanalytics/customentityrecognition

版本 2022-05-01 中的新增功能: begin_recognize_custom_entities 客户端方法。

begin_recognize_custom_entities(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], project_name: str, deployment_name: str, *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[RecognizeCustomEntitiesResult | DocumentError]]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式的 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

project_name
str
必需

必需。 此字段指示模型的项目名称。

deployment_name
str
必需

此字段指示模型的部署名称。

language
str

整个批语言的 2 个字母 ISO 639-1 表示形式。 例如,将“en”用于英语;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

show_stats
bool

如果设置为 true,则响应将包含文档级统计信息。

disable_service_logs
bool

如果设置为 true,则选择退出在服务端记录文本输入进行故障排除。 默认情况下,语言服务会记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 将此参数设置为 true 会禁用输入日志记录,并可能限制我们修正出现的问题的能力。 有关详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及 Microsoft https://www.microsoft.com/ai/responsible-ai负责任 AI 原则。

string_index_type
str

指定用于解释字符串偏移量的方法。 UnicodeCodePoint 是默认的 Python 编码。 若要替代 Python 默认值,还可以传入 Utf16CodeUnitTextElement_v8。 有关其他信息,请参阅 https://aka.ms/text-analytics-offsets

polling_interval
int

如果没有 Retry-After 标头,则 LRO 操作的两次轮询之间的等待时间。 默认为 5 秒。

continuation_token
str

对轮询器对象调用 continuation_token () ,将长时间运行的操作 (LRO) 状态保存到不透明的令牌中。 将值作为continuation_token关键字 (keyword) 参数传递,以从保存状态重启 LRO。

display_name
str

要为请求的分析设置的可选显示名称。

返回

TextAnalysisLROPoller 的实例。 在此对象上调用 result () 以返回 和 DocumentErrorRecognizeCustomEntitiesResult异类分页。

返回类型

例外

示例

识别一批文档中的自定义实体。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]
   project_name = os.environ["CUSTOM_ENTITIES_PROJECT_NAME"]
   deployment_name = os.environ["CUSTOM_ENTITIES_DEPLOYMENT_NAME"]
   path_to_sample_document = os.path.abspath(
       os.path.join(
           os.path.abspath(__file__),
           "..",
           "./text_samples/custom_entities_sample.txt",
       )
   )

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   with open(path_to_sample_document) as fd:
       document = [fd.read()]

   poller = text_analytics_client.begin_recognize_custom_entities(
       document,
       project_name=project_name,
       deployment_name=deployment_name
   )

   document_results = poller.result()
   for custom_entities_result in document_results:
       if custom_entities_result.kind == "CustomEntityRecognition":
           for entity in custom_entities_result.entities:
               print(
                   "Entity '{}' has category '{}' with confidence score of '{}'".format(
                       entity.text, entity.category, entity.confidence_score
                   )
               )
       elif custom_entities_result.is_error is True:
           print("...Is an error with code '{}' and message '{}'".format(
               custom_entities_result.error.code, custom_entities_result.error.message
               )
           )

begin_single_label_classify

启动长时间运行的自定义单标签分类操作。

有关自定义功能的区域支持以及如何训练模型以对文档进行分类的信息,请参阅 https://aka.ms/azsdk/textanalytics/customfunctionalities

版本 2022-05-01 中的新增功能: begin_single_label_classify 客户端方法。

begin_single_label_classify(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], project_name: str, deployment_name: str, *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[ClassifyDocumentResult | DocumentError]]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项目指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

project_name
str
必需

必需。 此字段指示模型的项目名称。

deployment_name
str
必需

此字段指示模型的部署名称。

language
str

整个批次语言的 2 个字母 ISO 639-1 表示形式。 例如,对英语使用“en”;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

show_stats
bool

如果设置为 true,则响应将包含文档级别统计信息。

disable_service_logs
bool

如果设置为 true,则选择退出在服务端记录文本输入进行故障排除。 默认情况下,语言服务会记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 将此参数设置为 true 会禁用输入日志记录,并可能限制我们修正出现的问题的能力。 有关详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及 Microsoft https://www.microsoft.com/ai/responsible-ai负责任 AI 原则。

polling_interval
int

如果没有 Retry-After 标头,则 LRO 操作的两次轮询之间的等待时间。 默认为 5 秒。

continuation_token
str

对轮询器对象调用 continuation_token () ,将长时间运行的操作 (LRO) 状态保存到不透明的令牌中。 将值作为continuation_token关键字 (keyword) 参数传递,以从保存状态重启 LRO。

display_name
str

要为请求的分析设置的可选显示名称。

返回

TextAnalysisLROPoller 的实例。 在此对象上调用 result () 以返回 和 DocumentErrorClassifyDocumentResult异类分页。

返回类型

例外

示例

对一批文档执行单标签分类。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]
   project_name = os.environ["SINGLE_LABEL_CLASSIFY_PROJECT_NAME"]
   deployment_name = os.environ["SINGLE_LABEL_CLASSIFY_DEPLOYMENT_NAME"]
   path_to_sample_document = os.path.abspath(
       os.path.join(
           os.path.abspath(__file__),
           "..",
           "./text_samples/custom_classify_sample.txt",
       )
   )

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   with open(path_to_sample_document) as fd:
       document = [fd.read()]

   poller = text_analytics_client.begin_single_label_classify(
       document,
       project_name=project_name,
       deployment_name=deployment_name
   )

   document_results = poller.result()
   for doc, classification_result in zip(document, document_results):
       if classification_result.kind == "CustomDocumentClassification":
           classification = classification_result.classifications[0]
           print("The document text '{}' was classified as '{}' with confidence score {}.".format(
               doc, classification.category, classification.confidence_score)
           )
       elif classification_result.is_error is True:
           print("Document text '{}' has an error with code '{}' and message '{}'".format(
               doc, classification_result.error.code, classification_result.error.message
           ))

close

关闭客户端打开的套接字。 使用客户端作为上下文管理器时,不需要调用此方法。

close() -> None

例外

detect_language

检测一批文档的语言。

返回检测到的语言和介于零和 1 之间的数字分数。 分数接近 1 表示 100% 确定所标识的语言是正确的。 有关已启用的语言列表,请参阅 https://aka.ms/talangs

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能:disable_service_logs 关键字 (keyword) 参数。

detect_language(documents: List[str] | List[DetectLanguageInput] | List[Dict[str, str]], *, country_hint: str | None = None, disable_service_logs: bool | None = None, model_version: str | None = None, show_stats: bool | None = None, **kwargs: Any) -> List[DetectLanguageResult | DocumentError]

参数

documents
list[str] 或 list[DetectLanguageInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项目指定 ID 和country_hint,则必须使用 作为输入列表[DetectLanguageInput] 或的听写表示形式 DetectLanguageInput列表,例如 {“id”: “1”, “country_hint”: “us”, “text”: “hello world”}

country_hint
str

整个批次的原产国提示。 接受 ISO 3166-1 alpha-2 指定的两个字母国家/地区代码。 每文档国家/地区提示优先于整个批处理提示。 默认为“US”。 如果不想使用国家/地区提示,请传递字符串“none”。

model_version
str

用于分析的模型版本,例如“latest”。 如果未指定模型版本,API 将默认为最新的非预览版本。 有关详细信息,请参阅此处: https://aka.ms/text-analytics-model-versioning

show_stats
bool

如果设置为 true,则响应将在文档级响应的 统计信息 字段中包含文档级统计信息。

disable_service_logs
bool

如果设置为 true,则选择退出在服务端记录文本输入进行故障排除。 默认情况下,语言服务会记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 将此参数设置为 true 会禁用输入日志记录,并可能限制我们修正出现的问题的能力。 有关详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及 Microsoft https://www.microsoft.com/ai/responsible-ai负责任 AI 原则。

返回

DocumentError 的组合列表DetectLanguageResult,按原始文档的传递顺序排列。

返回类型

例外

示例

检测一批文档中的语言。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
   documents = [
       """
       The concierge Paulette was extremely helpful. Sadly when we arrived the elevator was broken, but with Paulette's help we barely noticed this inconvenience.
       She arranged for our baggage to be brought up to our room with no extra charge and gave us a free meal to refurbish all of the calories we lost from
       walking up the stairs :). Can't say enough good things about my experience!
       """,
       """
       最近由于工作压力太大,我们决定去富酒店度假。那儿的温泉实在太舒服了,我跟我丈夫都完全恢复了工作前的青春精神!加油!
       """
   ]

   result = text_analytics_client.detect_language(documents)
   reviewed_docs = [doc for doc in result if not doc.is_error]

   print("Let's see what language each review is in!")

   for idx, doc in enumerate(reviewed_docs):
       print("Review #{} is in '{}', which has ISO639-1 name '{}'\n".format(
           idx, doc.primary_language.name, doc.primary_language.iso6391_name
       ))

extract_key_phrases

从一批文档中提取关键短语。

返回表示输入文本中关键短语的字符串列表。 例如,对于输入文本“食物很美味,有出色的工作人员”,API 返回main谈话点:“食物”和“美妙的员工”

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能:disable_service_logs 关键字 (keyword) 参数。

extract_key_phrases(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, disable_service_logs: bool | None = None, language: str | None = None, model_version: str | None = None, show_stats: bool | None = None, **kwargs: Any) -> List[ExtractKeyPhrasesResult | DocumentError]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项目指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

language
str

整个批次语言的 2 个字母 ISO 639-1 表示形式。 例如,对英语使用“en”;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

model_version
str

用于分析的模型版本,例如“latest”。 如果未指定模型版本,API 将默认为最新的非预览版本。 有关详细信息,请参阅此处: https://aka.ms/text-analytics-model-versioning

show_stats
bool

如果设置为 true,则响应将在文档级响应的 统计信息 字段中包含文档级统计信息。

disable_service_logs
bool

如果设置为 true,则选择退出在服务端记录文本输入进行故障排除。 默认情况下,语言服务会记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 将此参数设置为 true 会禁用输入日志记录,并可能限制我们修正出现的问题的能力。 有关详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及 Microsoft https://www.microsoft.com/ai/responsible-ai负责任 AI 原则。

返回

DocumentError 的组合列表ExtractKeyPhrasesResult,按原始文档的传递顺序排列。

返回类型

例外

示例

提取一批文档中的关键短语。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
   articles = [
       """
       Washington, D.C. Autumn in DC is a uniquely beautiful season. The leaves fall from the trees
       in a city chock-full of forests, leaving yellow leaves on the ground and a clearer view of the
       blue sky above...
       """,
       """
       Redmond, WA. In the past few days, Microsoft has decided to further postpone the start date of
       its United States workers, due to the pandemic that rages with no end in sight...
       """,
       """
       Redmond, WA. Employees at Microsoft can be excited about the new coffee shop that will open on campus
       once workers no longer have to work remotely...
       """
   ]

   result = text_analytics_client.extract_key_phrases(articles)
   for idx, doc in enumerate(result):
       if not doc.is_error:
           print("Key phrases in article #{}: {}".format(
               idx + 1,
               ", ".join(doc.key_phrases)
           ))

recognize_entities

识别一批文档的实体。

识别文本中的实体并将其分类为人员、地点、组织、日期/时间、数量、百分比、货币等。 有关支持的实体类型的列表,检查:https://aka.ms/taner

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能:disable_service_logsstring_index_type关键字 (keyword) 参数。

recognize_entities(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, disable_service_logs: bool | None = None, language: str | None = None, model_version: str | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> List[RecognizeEntitiesResult | DocumentError]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项目指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

language
str

整个批次语言的 2 个字母 ISO 639-1 表示形式。 例如,对英语使用“en”;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

model_version
str

用于分析的模型版本,例如“latest”。 如果未指定模型版本,API 将默认为最新的非预览版本。 有关详细信息,请参阅此处: https://aka.ms/text-analytics-model-versioning

show_stats
bool

如果设置为 true,则响应将在文档级响应的 统计信息 字段中包含文档级统计信息。

string_index_type
str

指定用于解释字符串偏移量的方法。 UnicodeCodePoint 是默认的 Python 编码。 若要替代 Python 默认值,还可以传入 Utf16CodeUnitTextElement_v8。 有关其他信息,请参阅 https://aka.ms/text-analytics-offsets

disable_service_logs
bool

如果设置为 true,则选择不将文本输入记录在服务端进行故障排除。 默认情况下,语言服务会记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 将此参数设置为 true 会禁用输入日志记录,并可能限制我们修正所发生问题的能力。 有关更多详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及上的 https://www.microsoft.com/ai/responsible-aiMicrosoft 负责任 AI 原则。

返回

DocumentError 的组合RecognizeEntitiesResult列表,按原始文档的传入顺序排列。

返回类型

例外

示例

识别一批文档中的实体。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
   reviews = [
       """I work for Foo Company, and we hired Contoso for our annual founding ceremony. The food
       was amazing and we all can't say enough good words about the quality and the level of service.""",
       """We at the Foo Company re-hired Contoso after all of our past successes with the company.
       Though the food was still great, I feel there has been a quality drop since their last time
       catering for us. Is anyone else running into the same problem?""",
       """Bar Company is over the moon about the service we received from Contoso, the best sliders ever!!!!"""
   ]

   result = text_analytics_client.recognize_entities(reviews)
   result = [review for review in result if not review.is_error]
   organization_to_reviews: typing.Dict[str, typing.List[str]] = {}

   for idx, review in enumerate(result):
       for entity in review.entities:
           print(f"Entity '{entity.text}' has category '{entity.category}'")
           if entity.category == 'Organization':
               organization_to_reviews.setdefault(entity.text, [])
               organization_to_reviews[entity.text].append(reviews[idx])

   for organization, reviews in organization_to_reviews.items():
       print(
           "\n\nOrganization '{}' has left us the following review(s): {}".format(
               organization, "\n\n".join(reviews)
           )
       )

recognize_linked_entities

从已知知识库识别一批文档的链接实体。

识别和消除文本 (中的每个实体的身份,例如,确定“火星”一词的出现是指行星,还是罗马战神) 。 识别的实体与已知知识库(如维基百科)的 URL 相关联。

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能:disable_service_logsstring_index_type关键字 (keyword) 参数。

recognize_linked_entities(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, disable_service_logs: bool | None = None, language: str | None = None, model_version: str | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> List[RecognizeLinkedEntitiesResult | DocumentError]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式的 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

language
str

整个批语言的 2 个字母 ISO 639-1 表示形式。 例如,将“en”用于英语;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

model_version
str

用于分析的模型版本,例如“latest”。 如果未指定模型版本,API 将默认为最新的非预览版本。 有关详细信息,请参阅此处: https://aka.ms/text-analytics-model-versioning

show_stats
bool

如果设置为 true,则响应将在文档级响应的 统计信息 字段中包含文档级统计信息。

string_index_type
str

指定用于解释字符串偏移量的方法。 UnicodeCodePoint 是默认的 Python 编码。 若要替代 Python 默认值,还可以传入 Utf16CodeUnitTextElement_v8。 有关其他信息,请参阅 https://aka.ms/text-analytics-offsets

disable_service_logs
bool

如果设置为 true,则选择不将文本输入记录在服务端进行故障排除。 默认情况下,语言服务会记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 将此参数设置为 true 会禁用输入日志记录,并可能限制我们修正所发生问题的能力。 有关更多详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及上的 https://www.microsoft.com/ai/responsible-aiMicrosoft 负责任 AI 原则。

返回

DocumentError 的组合RecognizeLinkedEntitiesResult列表,按原始文档的传入顺序排列。

返回类型

例外

示例

识别一批文档中的链接实体。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
   documents = [
       """
       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 January 1979, but is now
       headquartered in Redmond.
       """
   ]

   result = text_analytics_client.recognize_linked_entities(documents)
   docs = [doc for doc in result if not doc.is_error]

   print(
       "Let's map each entity to it's Wikipedia article. I also want to see how many times each "
       "entity is mentioned in a document\n\n"
   )
   entity_to_url = {}
   for doc in docs:
       for entity in doc.entities:
           print("Entity '{}' has been mentioned '{}' time(s)".format(
               entity.name, len(entity.matches)
           ))
           if entity.data_source == "Wikipedia":
               entity_to_url[entity.name] = entity.url

recognize_pii_entities

识别包含一批文档的个人信息的实体。

返回文档中) (“SSN”、“银行帐户”等个人信息实体的列表。 有关支持的实体类型的列表,检查 https://aka.ms/azsdk/language/pii

有关服务数据限制,请参阅 https://aka.ms/azsdk/textanalytics/data-limits

版本 v3.1 中的新增功能: recognize_pii_entities 客户端方法。

recognize_pii_entities(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, categories_filter: List[str | PiiEntityCategory] | None = None, disable_service_logs: bool | None = None, domain_filter: str | PiiEntityDomain | None = None, language: str | None = None, model_version: str | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> List[RecognizePiiEntitiesResult | DocumentError]

参数

documents
list[str] 或 list[TextDocumentInput] 或 list[dict[str, str]]
必需

要作为此批处理的一部分处理的文档集。 如果要按项指定 ID 和语言,则必须使用 作为输入 list[TextDocumentInput] 或的听写表示形式的 TextDocumentInput列表,例如 {“id”: “1”, “language”: “en”, “text”: “hello world”}

language
str

整个批语言的 2 个字母 ISO 639-1 表示形式。 例如,将“en”用于英语;西班牙语等的“es”。如果未设置,则默认使用英语的“en”。 每文档语言优先于整个批处理语言。 有关语言 API 中支持的语言,请参阅 https://aka.ms/talangs

model_version
str

用于分析的模型版本,例如“latest”。 如果未指定模型版本,API 将默认为最新的非预览版本。 有关详细信息,请参阅此处: https://aka.ms/text-analytics-model-versioning

show_stats
bool

如果设置为 true,则响应将在文档级响应的 统计信息 字段中包含文档级统计信息。

domain_filter
strPiiEntityDomain

将响应实体筛选为仅包含在指定域中的实体。 也就是说,如果设置为“phi”,将仅返回受保护医疗保健信息域中的实体。 有关详细信息,请参阅https://aka.ms/azsdk/language/pii

categories_filter
list[strPiiEntityCategory]

可以传入要筛选出的特定 PII 实体类别的列表,而不是筛选所有 PII 实体类别。例如,如果只想筛选出文档中的美国社会安全号码,则可以传入此 kwarg 的 [PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER]。

string_index_type
str

指定用于解释字符串偏移量的方法。 UnicodeCodePoint 是默认的 Python 编码。 若要替代 Python 默认值,还可以传入 Utf16CodeUnitTextElement_v8。 有关其他信息,请参阅 https://aka.ms/text-analytics-offsets

disable_service_logs
bool

默认为 true,这意味着语言服务不会在服务端记录输入文本以便进行故障排除。 如果设置为 False,则语言服务将记录输入文本 48 小时,仅用于排查在提供服务的自然语言处理功能时出现的问题。 有关更多详细信息,请参阅 上的 https://aka.ms/cs-compliance 认知服务合规性和隐私说明,以及上的 https://www.microsoft.com/ai/responsible-aiMicrosoft 负责任 AI 原则。

返回

DocumentError 的组合RecognizePiiEntitiesResult列表,按原始文档的传入顺序排列。

返回类型

例外

示例

识别一批文档中的个人身份信息实体。


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

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint, credential=AzureKeyCredential(key)
   )
   documents = [
       """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
       555-555-5555. They are originally from Brazil and have Brazilian CPF number 998.214.865-68"""
   ]

   result = text_analytics_client.recognize_pii_entities(documents)
   docs = [doc for doc in result if not doc.is_error]

   print(
       "Let's compare the original document with the documents after redaction. "
       "I also want to comb through all of the entities that got redacted"
   )
   for idx, doc in enumerate(docs):
       print(f"Document text: {documents[idx]}")
       print(f"Redacted document text: {doc.redacted_text}")
       for entity in doc.entities:
           print("...Entity '{}' with category '{}' got redacted".format(
               entity.text, entity.category
           ))