Share via


快速入門:使用關鍵片語擷取客戶端連結庫和 REST API

參考檔 | 其他範例 | 套件 (NuGet) | 連結庫原始程式碼

使用此快速入門,使用適用於 .NET 的用戶端連結庫建立關鍵片語擷取應用程式。 在下列範例中,您將建立 C# 應用程式,以識別文字中找到的關鍵詞和片語。

提示

您可以使用 Language Studio 來嘗試語言服務功能,而不需要撰寫程式代碼。

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • Visual Studio IDE
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立語言資源,以取得您的密鑰和端點。 在其部署後,選取 [前往資源]
    • 您需要從您建立的資源取得密鑰和端點,才能將應用程式連線到 API。 您稍後會在快速入門中將金鑰和端點貼到下列程式代碼中。
    • 您可以使用免費定價層 (Free F0) 來試用服務,之後可升級至付費層以用於實際執行環境。
  • 若要使用分析功能,您需要具有標準 (S) 定價層的語言資源。

設定

建立新的 .NET Core 應用程式

使用 Visual Studio IDE,建立新的 .NET Core 控制台應用程式。 這會建立具有單一 C# 原始程序檔的 「Hello World」 專案: program.cs

以滑鼠右鍵按兩下 方案總管中的解決方案,然後選取 [管理 NuGet 套件],以安裝客戶端連結庫。 開啟的套件管理員中,選取 [ 瀏覽 ] 並搜尋 Azure.AI.TextAnalytics。 選取 [版本 5.2.0],然後 選取 [安裝]。 您也可以使用 封裝管理員 主控台

程式碼範例

將下列程式代碼複製到您的 program.cs 檔案。 請記得將變數取代 key 為您的資源索引鍵,並將變數取代 endpoint 為您資源的端點。 然後執行程式碼。

重要

前往 Azure 入口網站。 如果您在成功部署必要條件一節中建立的語言資源,請按兩下 [後續步驟] 底下的 [移至資源] 按鈕。 您可以在 [資源管理] 底下瀏覽至資源的 [金鑰和端點] 頁面,以尋找您的金鑰和端點

重要

完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

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

namespace KeyPhraseExtractionExample
{
    class Program
    {
        private static readonly AzureKeyCredential credentials = new AzureKeyCredential("replace-with-your-key-here");
        private static readonly Uri endpoint = new Uri("replace-with-your-endpoint-here");

        // Example method for extracting key phrases from text
        static void KeyPhraseExtractionExample(TextAnalyticsClient client)
        {
            var response = client.ExtractKeyPhrases(@"Dr. Smith has a very modern medical office, and she has great staff.");

            // Printing key phrases
            Console.WriteLine("Key phrases:");

            foreach (string keyphrase in response.Value)
            {
                Console.WriteLine($"\t{keyphrase}");
            }
        }

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

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

    }
}

輸出

Key phrases:
    modern medical office
    Dr. Smith
    great staff

參考檔 | 其他範例 | 套件 (Maven) | 連結庫原始程式碼

使用此快速入門,使用適用於 Java 的用戶端連結庫建立關鍵片語擷取應用程式。 在下列範例中,您將建立 Java 應用程式,以識別文字中找到的關鍵詞和片語。

提示

您可以使用 Language Studio 來嘗試語言服務功能,而不需要撰寫程式代碼。

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 具有 8 版或更新版本的 Java 開發工具套件 (JDK)
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立語言資源,以取得您的密鑰和端點。 在其部署後,選取 [前往資源]
    • 您需要從您建立的資源取得密鑰和端點,才能將應用程式連線到 API。 您稍後會在快速入門中將金鑰和端點貼到下列程式代碼中。
    • 您可以使用免費定價層 (Free F0) 來試用服務,之後可升級至付費層以用於實際執行環境。
  • 若要使用分析功能,您需要具有標準 (S) 定價層的語言資源。

設定

新增 用戶端程式庫

在慣用的 IDE 或開發環境中建立 Maven 專案。 然後將下列相依性新增至專案的 pom.xml 檔案。 您可以在在線找到其他建置工具的實作語法

<dependencies>
     <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-textanalytics</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

程式碼範例

建立名為 Example.java的 Java 檔案。 開啟檔案並複製下列程序代碼。 請記得將變數取代 key 為您的資源索引鍵,並將變數取代 endpoint 為您資源的端點。 然後執行程式碼。

重要

前往 Azure 入口網站。 如果您在成功部署必要條件一節中建立的語言資源,請按兩下 [後續步驟] 底下的 [移至資源] 按鈕。 您可以在 [資源管理] 底下瀏覽至資源的 [金鑰和端點] 頁面,以尋找您的金鑰和端點

重要

完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

import com.azure.core.credential.AzureKeyCredential;
import com.azure.ai.textanalytics.TextAnalyticsClientBuilder;
import com.azure.ai.textanalytics.TextAnalyticsClient;


public class Example {

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

    public static void main(String[] args) {
        TextAnalyticsClient client = authenticateClient(KEY, ENDPOINT);
        extractKeyPhrasesExample(client);
    }
    // Method to authenticate the client object with your key and endpoint
    static TextAnalyticsClient authenticateClient(String key, String endpoint) {
        return new TextAnalyticsClientBuilder()
                .credential(new AzureKeyCredential(key))
                .endpoint(endpoint)
                .buildClient();
    }
    // Example method for extracting key phrases from text
    static void extractKeyPhrasesExample(TextAnalyticsClient client)
    {
        // The text to be analyzed
        String text = "Dr. Smith has a very modern medical office, and she has great staff.";

        System.out.printf("Recognized phrases: %n");
        for (String keyPhrase : client.extractKeyPhrases(text)) {
            System.out.printf("%s%n", keyPhrase);
        }
    }
}

輸出

Recognized phrases: 

modern medical office
Dr. Smith
great staff

參考檔 | 其他範例 | 套件 (npm) | 連結庫原始程式碼

使用此快速入門來建立具有用戶端連結庫的關鍵片語擷取應用程式,以進行Node.js。 在下列範例中,您將建立 JavaScript 應用程式,以識別文字中找到的關鍵詞和片語。

提示

您可以使用 Language Studio 來嘗試語言服務功能,而不需要撰寫程式代碼。

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • Node.js v14 LTS 或更新版本
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立語言資源,以取得您的密鑰和端點。 在其部署後,選取 [前往資源]
    • 您需要從您建立的資源取得密鑰和端點,才能將應用程式連線到 API。 您稍後會在快速入門中將金鑰和端點貼到下列程式代碼中。
    • 您可以使用免費定價層 (Free F0) 來試用服務,之後可升級至付費層以用於實際執行環境。
  • 若要使用分析功能,您需要具有標準 (S) 定價層的語言資源。

設定

建立新的Node.js應用程式

在主控台視窗中(例如 cmd、PowerShell 或 Bash),為您的應用程式建立新的目錄,然後流覽至它。

mkdir myapp 

cd myapp

npm init執行 命令以使用 package.json 檔案建立節點應用程式。

npm init

安裝客戶端連結庫

安裝 npm 套件:

npm install @azure/ai-language-text

程式碼範例

開啟檔案並複製下列程序代碼。 請記得將變數取代 key 為您的資源索引鍵,並將變數取代 endpoint 為您資源的端點。 然後執行程式碼。

重要

前往 Azure 入口網站。 如果您在成功部署必要條件一節中建立的語言資源,請按兩下 [後續步驟] 底下的 [移至資源] 按鈕。 您可以在 [資源管理] 底下瀏覽至資源的 [金鑰和端點] 頁面,以尋找您的金鑰和端點

重要

完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

"use strict";

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");
const key = '<paste-your-key-here>';
const endpoint = '<paste-your-endpoint-here>';

//example sentence for performing key phrase extraction
const documents = ["Dr. Smith has a very modern medical office, and she has great staff."];

//example of how to use the client to perform entity linking on a document
async function main() {
    console.log("== key phrase extraction sample ==");
  
    const client = new TextAnalysisClient(endpoint, new AzureKeyCredential(key));
  
    const results = await client.analyze("KeyPhraseExtraction", documents);
  
    for (const result of results) {
      console.log(`- Document ${result.id}`);
      if (!result.error) {
        console.log("\tKey phrases:");
        for (const phrase of result.keyPhrases) {
          console.log(`\t- ${phrase}`);
        }
      } else {
        console.error("  Error:", result.error);
      }
    }
  }
  
  main().catch((err) => {
    console.error("The sample encountered an error:", err);
  });
  

輸出

== key phrase extraction sample ==
- Document 0
    Key phrases:
    - modern medical office
    - Dr. Smith
    - great staff

參考檔 | 其他範例 | 套件 (PyPi) | 連結庫原始程式碼

使用此快速入門,透過適用於 Python 的用戶端連結庫建立關鍵片語擷取應用程式。 在下列範例中,您將建立 Python 應用程式,以識別文字中找到的關鍵詞和片語。

提示

您可以使用 Language Studio 來嘗試語言服務功能,而不需要撰寫程式代碼。

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • Python 3.8 或更新版本
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立語言資源,以取得您的密鑰和端點。 在其部署後,選取 [前往資源]
    • 您需要從您建立的資源取得密鑰和端點,才能將應用程式連線到 API。 您稍後會在快速入門中將金鑰和端點貼到下列程式代碼中。
    • 您可以使用免費定價層 (Free F0) 來試用服務,之後可升級至付費層以用於實際執行環境。
  • 若要使用分析功能,您需要具有標準 (S) 定價層的語言資源。

設定

安裝客戶端連結庫

安裝 Python 之後,您可以使用下列項目來安裝用戶端連結庫:

pip install azure-ai-textanalytics==5.2.0

程式碼範例

建立新的 Python 檔案,並複製下列程式代碼。 請記得將變數取代 key 為您的資源索引鍵,並將變數取代 endpoint 為您資源的端點。 然後執行程式碼。

重要

前往 Azure 入口網站。 如果您在成功部署必要條件一節中建立的語言資源,請按兩下 [後續步驟] 底下的 [移至資源] 按鈕。 您可以在 [資源管理] 底下瀏覽至資源的 [金鑰和端點] 頁面,以尋找您的金鑰和端點

重要

完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

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

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

# Authenticate the client using your key and endpoint 
def authenticate_client():
    ta_credential = AzureKeyCredential(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint, 
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

def key_phrase_extraction_example(client):

    try:
        documents = ["Dr. Smith has a very modern medical office, and she has great staff."]

        response = client.extract_key_phrases(documents = documents)[0]

        if not response.is_error:
            print("\tKey Phrases:")
            for phrase in response.key_phrases:
                print("\t\t", phrase)
        else:
            print(response.id, response.error)

    except Exception as err:
        print("Encountered exception. {}".format(err))
        
key_phrase_extraction_example(client)

輸出

Key Phrases:
    modern medical office
    Dr. Smith
    great staff

參考檔

使用此快速入門,使用 REST API 傳送關鍵片語擷取要求。 在下列範例中,您將使用 cURL 來識別文字中找到的關鍵詞和片語。

提示

您可以使用 Language Studio 來嘗試語言服務功能,而不需要撰寫程式代碼。

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 最新版的 cURL
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立語言資源,以取得您的密鑰和端點。 在其部署後,選取 [前往資源]
    • 您需要從您建立的資源取得密鑰和端點,才能將應用程式連線到 API。 您稍後會在快速入門中將金鑰和端點貼到下列程式代碼中。
    • 您可以使用免費定價層 (Free F0) 來試用服務,之後可升級至付費層以用於實際執行環境。

注意

  • 下列BASH範例使用 \ 行接續字元。 如果您的主控台或終端機使用不同的行接續字元,請使用該字元。
  • 您可以在 GitHub找到語言特定範例。
  • 移至 Azure 入口網站,並尋找您在必要條件中建立之語言資源的密鑰和端點。 它們會位於資源管理的 [金鑰和端點] 頁面上。 然後將下列程式代碼中的字串取代為您的金鑰和端點。 若要呼叫 API,您需要下列資訊:
parameter 描述
-X POST <endpoint> 指定用於存取 API 的端點。
-H Content-Type: application/json 傳送 JSON 資料的內容類型。
-H "Ocp-Apim-Subscription-Key:<key> 指定用來存取 API 的金鑰。
-d <documents> 包含您要傳送之檔的 JSON。

下列 cURL 命令是從 BASH 殼層執行。 使用您自己的資源名稱、資源索引鍵和 JSON 值來編輯這些命令。

關鍵片語擷取

  1. 將命令複製到文字編輯器中。
  2. 視需要在命令中進行下列變更:
    1. 以您的索引鍵取代 值 <your-language-resource-key>
    2. 將要求URL <your-language-resource-endpoint> 的第一個部分取代為您的端點URL。
  3. 開啟 [命令提示字元] 視窗。
  4. 將命令從文字編輯器貼到命令提示字元視窗中,然後執行命令。
curl -i -X POST https://<your-language-resource-endpoint>/language/:analyze-text?api-version=2022-05-01 \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key: <your-language-resource-key>" \
-d \
'
{
    "kind": "KeyPhraseExtraction",
    "parameters": {
        "modelVersion": "latest"
    },
    "analysisInput":{
        "documents":[
            {
                "id":"1",
                "language":"en",
                "text": "Dr. Smith has a very modern medical office, and she has great staff."
            }
        ]
    }
}
'

JSON 回應

{
	"kind": "KeyPhraseExtractionResults",
	"results": {
		"documents": [{
			"id": "1",
			"keyPhrases": ["modern medical office", "Dr. Smith", "great staff"],
			"warnings": []
		}],
		"errors": [],
		"modelVersion": "2021-06-01"
	}
}

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

下一步