Share via


TextAnalyticsClient 類別

語言服務 API 是一套自然語言處理, (NLP) 使用最佳 Microsoft 機器學習演算法所建置的技能。 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 關鍵字引數。

begin_abstract_summary

啟動長時間執行的抽象摘要作業。

如需抽象摘要的概念性討論,請參閱服務檔: https://learn.microsoft.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 版的新功能:RecognizeCustomEntitiesActionSingleLabelClassifyAction、MultiLabelClassifyActionAnalyzeHealthcareEntitiesAction輸入選項和對應的RecognizeCustomEntitiesResultClassifyDocumentResultAnalyzeHealthcareEntitiesResult結果物件

2023-04-01 版的新功能:ExtractiveSummaryAction 和 AbstractiveSummaryAction輸入選項,以及對應的ExtractiveSummaryResultAbstractiveSummaryResult結果物件。

begin_analyze_healthcare_entities

分析醫療保健實體,並識別一批次檔中這些實體之間的關聯性。

實體會與現有知識庫中找到的參考相關聯,例如 UMLS、CHV、MSH 等。

我們也擷取實體之間找到的關聯,例如,在「主體採用 100 mg of ibuprofen」中,我們會擷取 「100 mg」 燈泡與 「ibuprofen」 藥物之間的關聯性。

v3.1 版的新功能: begin_analyze_healthcare_entities 用戶端方法。

2022-05-01 版的新功能: display_name 關鍵字引數。

begin_extract_summary

啟動長時間執行的擷取摘要作業。

如需擷取摘要的概念性討論,請參閱服務檔: https://learn.microsoft.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 的分數表示識別語言為 true 的 100% 確定性。 如需已啟用的語言清單,請參閱 https://aka.ms/talangs

如需服務資料限制,請參閱 https://aka.ms/azsdk/textanalytics/data-limits

v3.1 版的新功能: disable_service_logs 關鍵字引數。

extract_key_phrases

從檔批次擷取關鍵字組。

傳回字串清單,指出輸入文字中的關鍵字組。 例如,針對輸入文字「The food was the food was the main talking points」 ,API 會傳回主要交談點:「food」和「很棒的員工」

如需服務資料限制,請參閱 https://aka.ms/azsdk/textanalytics/data-limits

v3.1 版的新功能: disable_service_logs 關鍵字引數。

recognize_entities

辨識檔批次的實體。

將文字中的實體識別並分類為人員、地點、組織、日期/時間、數量、百分比、貨幣等等。 如需支援的實體類型清單,請檢查: https://aka.ms/taner

如需服務資料限制,請參閱 https://aka.ms/azsdk/textanalytics/data-limits

v3.1 版的新功能: disable_service_logsstring_index_type 關鍵字引數。

recognize_linked_entities

從已知知識庫辨識檔批次的連結實體。

識別並厘清在文字 (中找到之每個實體的身分識別,例如,判斷 Mars 一詞是否參照行星,或判斷 Mars 一詞是否參照到行星,或判斷羅馬世界) 。 辨識的實體會與已知知識庫的 URL 相關聯,例如 Wikipedia。

如需服務資料限制,請參閱 https://aka.ms/azsdk/textanalytics/data-limits

v3.1 版的新功能: disable_service_logsstring_index_type 關鍵字引數。

recognize_pii_entities

辨識包含檔批次個人資訊的實體。

傳回檔中 (「SSN」、「銀行帳戶」等) 的個人資訊實體清單。 如需支援的實體類型清單,請檢查 https://aka.ms/azsdk/language/pii

如需服務資料限制,請參閱 https://aka.ms/azsdk/textanalytics/data-limits

3.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 關鍵字引數。

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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 做為輸入 list[ TextDocumentInput ] 或的聽寫表示 TextDocumentInput 清單,例如 {「id」: 「1」, 「language」: 「en」、「text」: 「hello world」}

show_opinion_mining
bool

是否要採礦句子的意見,並針對產品或服務的各個層面進行更細微的分析, (也稱為以層面為基礎的情感分析) 。 如果設定為 true,則傳 SentenceSentiment 回的物件會有屬性 mined_opinions 包含此分析的結果。 僅適用于 API 3.1 版和版本。

language
str

整個批次語言的 2 個字母 ISO 639-1 標記法。 例如,使用 「en」 表示英文;西班牙文等的 「es」如果未設定,請使用 「en」 作為英文作為預設值。 每個檔語言的優先順序會高於整個批次語言。 如需語言 API 中支援的語言,請參閱 https://aka.ms/talangs

model_version
str

用於分析的模型版本,例如「最新」。 如果未指定模型版本,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-ai 的 Microsoft 負責任 AI 原則。

傳回

和 的合併清單 AnalyzeSentimentResultDocumentError 會依照原始檔案傳入的順序。

傳回類型

例外狀況

範例

分析一批次檔中的情感。


   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://learn.microsoft.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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 做為輸入 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]

用於分析的模型版本,例如「最新」。 如果未指定模型版本,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-ai 的 Microsoft 負責任 AI 原則。

polling_interval
int

如果沒有 Retry-After 標頭,則等候兩個 LRO 作業輪詢之間的時間。 預設為 5 秒。

continuation_token
str

在輪詢器物件上呼叫 continuation_token () ,將長時間執行的作業儲存 (LRO) 狀態為不透明權杖。 將值當做 continuation_token 關鍵字引數傳遞,以從儲存的狀態重新開機 LRO。

display_name
str

要為要求分析設定的選擇性顯示名稱。

傳回

TextAnalysisLROPoller 的實例。 在此物件上呼叫 result () 以傳回 和 AbstractiveSummaryResultDocumentError 的異質性可分頁。

傳回類型

例外狀況

範例

對一批次檔執行抽象摘要。


   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 版的新功能:RecognizeCustomEntitiesActionSingleLabelClassifyAction、MultiLabelClassifyActionAnalyzeHealthcareEntitiesAction輸入選項和對應的RecognizeCustomEntitiesResultClassifyDocumentResultAnalyzeHealthcareEntitiesResult結果物件

2023-04-01 版的新功能:ExtractiveSummaryAction 和 AbstractiveSummaryAction輸入選項,以及對應的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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 做為輸入 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 關鍵字引數傳遞,以從儲存的狀態重新開機 LRO。

傳回

TextAnalysisLROPoller 的實例。 在輪詢器物件上呼叫 result () 以傳回可分頁的異質清單清單。 這份清單會先依您輸入的檔排序,然後依您輸入的動作排序。 例如,如果您有檔輸入 [「Hello」、「world」] 和 actions RecognizeEntitiesActionAnalyzeSentimentAction ,在逐一查看清單清單時,您必須先逐一查看 「Hello」 檔的動作結果,取得 RecognizeEntitiesResult 「Hello」 的 ,然後 AnalyzeSentimentResult 取得 「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 mg of ibuprofen」中,我們會擷取 「100 mg」 燈泡與 「ibuprofen」 藥物之間的關聯性。

v3.1 版的新功能: begin_analyze_healthcare_entities 用戶端方法。

2022-05-01 版的新功能: display_name 關鍵字引數。

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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 做為輸入 list[ TextDocumentInput ] 或的聽寫表示 TextDocumentInput 清單,例如 {「id」: 「1」, 「language」: 「en」、「text」: 「hello world」}

model_version
str

用於分析的模型版本,例如「最新」。 如果未指定模型版本,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 關鍵字引數傳遞,以從儲存的狀態重新開機 LRO。

disable_service_logs
bool

預設值為 true,這表示語言服務不會在服務端記錄您的輸入文字以進行疑難排解。 如果設定為 False,則語言服務會記錄您的輸入文字 48 小時,只允許針對提供服務的自然語言處理函式的問題進行疑難排解。 如需其他詳細資料,請參閱 認知服務合規性和隱私權注意事項 https://aka.ms/cs-compliance ,以及 位於 https://www.microsoft.com/ai/responsible-ai 的 Microsoft 負責任 AI 原則。

傳回

AnalyzeHealthcareEntitiesLROPoller 的實例。 在此物件上呼叫 result () 以傳回 和 AnalyzeHealthcareEntitiesResultDocumentError 的異質性可分頁。

傳回類型

例外狀況

範例

辨識一批次檔中的醫療保健實體。


   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://learn.microsoft.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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 做為輸入 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]

用於分析的模型版本,例如「最新」。 如果未指定模型版本,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-ai 的 Microsoft 負責任 AI 原則。

polling_interval
int

如果沒有 Retry-After 標頭,則等候兩個 LRO 作業輪詢之間的時間。 預設為 5 秒。

continuation_token
str

在輪詢器物件上呼叫 continuation_token () ,將長時間執行的作業儲存 (LRO) 狀態為不透明權杖。 將值當做 continuation_token 關鍵字引數傳遞,以從儲存的狀態重新開機 LRO。

display_name
str

要為要求分析設定的選擇性顯示名稱。

傳回

TextAnalysisLROPoller 的實例。 在此物件上呼叫 result () 以傳回 和 ExtractiveSummaryResultDocumentError 的異質性可分頁。

傳回類型

例外狀況

範例

對一批次檔執行擷取摘要。


   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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 做為輸入 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-ai 的 Microsoft 負責任 AI 原則。

polling_interval
int

如果沒有 Retry-After 標頭,則等候兩個 LRO 作業輪詢之間的時間。 預設為 5 秒。

continuation_token
str

在輪詢器物件上呼叫 continuation_token () ,將長時間執行的作業儲存 (LRO) 狀態為不透明權杖。 將值當做 continuation_token 關鍵字引數傳遞,以從儲存的狀態重新開機 LRO。

display_name
str

要為要求分析設定的選擇性顯示名稱。

傳回

TextAnalysisLROPoller 的實例。 在此物件上呼叫 result () 以傳回 和 ClassifyDocumentResultDocumentError 的異質性可分頁。

傳回類型

例外狀況

範例

在一批次檔上執行多標籤分類。


   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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 做為輸入 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-ai 的 Microsoft 負責任 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 關鍵字引數傳遞,以從儲存的狀態重新開機 LRO。

display_name
str

要為要求分析設定的選擇性顯示名稱。

傳回

TextAnalysisLROPoller 的實例。 在此物件上呼叫 result () 以傳回 和 RecognizeCustomEntitiesResultDocumentError 的異質性可分頁。

傳回類型

例外狀況

範例

辨識一批次檔中的自訂實體。


   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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 做為輸入 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-ai 的 Microsoft 負責任 AI 原則。

polling_interval
int

如果沒有 Retry-After 標頭,則等候兩個 LRO 作業輪詢之間的時間。 預設為 5 秒。

continuation_token
str

在輪詢器物件上呼叫 continuation_token () ,將長時間執行的作業儲存 (LRO) 狀態為不透明權杖。 將值當做 continuation_token 關鍵字引數傳遞,以從儲存的狀態重新開機 LRO。

display_name
str

要為要求分析設定的選擇性顯示名稱。

傳回

TextAnalysisLROPoller 的實例。 在此物件上呼叫 result () 以傳回 和 ClassifyDocumentResultDocumentError 的異質性可分頁。

傳回類型

例外狀況

範例

在一批次檔上執行單一標籤分類。


   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 的分數表示識別語言為 true 的 100% 確定性。 如需已啟用的語言清單,請參閱 https://aka.ms/talangs

如需服務資料限制,請參閱 https://aka.ms/azsdk/textanalytics/data-limits

v3.1 版的新功能: disable_service_logs 關鍵字引數。

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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和country_hint,您必須使用 做為輸入 list[ DetectLanguageInput ] 或 的聽寫表示 DetectLanguageInput 清單,例如 {「id」: 「1」、「country_hint」、「us」、「text」、「hello world」}

country_hint
str

整個批次的來源國家/地區提示。 接受 ISO 3166-1 Alpha-2 所指定的兩個字母國家/地區代碼。 個別檔的國家/地區提示將優先于整個批次提示。 預設為 「US」。 如果您不想使用國家/地區提示,請傳遞字串 「none」。

model_version
str

用於分析的模型版本,例如「最新」。 如果未指定模型版本,API 會預設為最新的非預覽版本。 如需詳細資訊,請參閱這裡: https://aka.ms/text-analytics-model-versioning

show_stats
bool

如果設定為 true,回應將會在檔層級回應的 統計資料 欄位中包含檔層級統計資料。

disable_service_logs
bool

如果設定為 true,您可以選擇不要將文字輸入記錄在服務端進行疑難排解。 根據預設,語言服務會記錄您的輸入文字 48 小時,只允許針對提供服務的自然語言處理函式的問題進行疑難排解。 將此參數設定為 true,會停用輸入記錄,並可能會限制我們修復發生的問題。 如需其他詳細資料,請參閱 認知服務合規性和隱私權注意事項 https://aka.ms/cs-compliance ,以及 位於 https://www.microsoft.com/ai/responsible-ai 的 Microsoft 負責任 AI 原則。

傳回

和 的合併清單 DetectLanguageResultDocumentError 會依照原始檔案傳入的順序。

傳回類型

例外狀況

範例

偵測檔中的語言。


   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

從檔批次擷取關鍵字組。

傳回字串清單,指出輸入文字中的關鍵字組。 例如,針對輸入文字「The food was the food was the main talking points」 ,API 會傳回主要交談點:「food」和「很棒的員工」

如需服務資料限制,請參閱 https://aka.ms/azsdk/textanalytics/data-limits

v3.1 版的新功能: disable_service_logs 關鍵字引數。

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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 做為輸入 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

用於分析的模型版本,例如「最新」。 如果未指定模型版本,API 會預設為最新的非預覽版本。 如需詳細資訊,請參閱這裡: https://aka.ms/text-analytics-model-versioning

show_stats
bool

如果設定為 true,回應將會在檔層級回應的 統計資料 欄位中包含檔層級統計資料。

disable_service_logs
bool

如果設定為 true,您可以選擇不要將文字輸入記錄在服務端進行疑難排解。 根據預設,語言服務會記錄您的輸入文字 48 小時,只允許針對提供服務的自然語言處理函式的問題進行疑難排解。 將此參數設定為 true,會停用輸入記錄,並可能會限制我們修復發生的問題。 如需其他詳細資料,請參閱 認知服務合規性和隱私權注意事項 https://aka.ms/cs-compliance ,以及 位於 https://www.microsoft.com/ai/responsible-ai 的 Microsoft 負責任 AI 原則。

傳回

和 的合併清單 ExtractKeyPhrasesResultDocumentError 會依照原始檔案傳入的順序。

傳回類型

例外狀況

範例

擷取檔批次中的關鍵字組。


   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 關鍵字引數。

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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 做為輸入 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

用於分析的模型版本,例如「最新」。 如果未指定模型版本,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-ai Microsoft 負責任 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

從已知知識庫辨識檔批次的連結實體。

識別並厘清在文字 (中找到之每個實體的身分識別,例如,判斷 Mars 一詞是否參照行星,或判斷 Mars 一詞是否參照到行星,或判斷羅馬世界) 。 辨識的實體會與已知知識庫的 URL 相關聯,例如 Wikipedia。

如需服務資料限制,請參閱 https://aka.ms/azsdk/textanalytics/data-limits

v3.1 版的新功能: disable_service_logsstring_index_type 關鍵字引數。

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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 作為 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

要用於分析的模型版本,例如「最新」。 如果未指定模型版本,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-ai Microsoft 負責任 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

3.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]]
必要

要在此批次中處理的一組檔。 如果您想要以每個專案為基礎指定識別碼和語言,您必須使用 作為 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

要用於分析的模型版本,例如「最新」。 如果未指定模型版本,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-ai Microsoft 負責任 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
           ))