快速入門:使用 .NET SDK 和 C# 來呼叫文字分析服務Quickstart: Use the .NET SDK and C# to call the Text Analytics service

本快速入門可協助您開始使用適用於 .NET 的 Azure SDK 和 C# 來分析語言。This quickstart helps you begin using the Azure SDK for .NET and C# to analyze language. 雖然文字分析 REST API 與大部分程式設計語言相容,但 SDK 會提供簡單的方法,將服務整合到您的應用程式。Although the Text Analytics REST API is compatible with most programming languages, the SDK provides an easy way to integrate the service into your applications.

注意

GitHub 上有此範例的原始程式碼。The source code for this sample is available on GitHub.

如需技術詳細資料,請針對適用於 .NET 的 SDK 參閱文字分析參考For technical details, refer to the SDK for .NET Text Analytics reference.

必要條件Prerequisites

您也需要註冊時產生的端點和存取金鑰You also need the endpoint and access key that was generated for you during sign-up.

建立 Visual Studio 解決方案並安裝 SDKCreate the Visual Studio solution and install the SDK

  1. 建立新的主控台應用程式 (.NET Core) 專案。Create a new console app (.NET Core) project. 存取 Visual StudioAccess Visual Studio.
  2. 以滑鼠右鍵按一下方案,然後選取 [管理方案的 NuGet 套件] 。Right-click the solution and select Manage NuGet Packages for Solution.
  3. 選取 [瀏覽] 索引標籤。搜尋 Microsoft.Azure.CognitiveServices.Language.TextAnalyticsSelect the Browse tab. Search for Microsoft.Azure.CognitiveServices.Language.TextAnalytics.

驗證您的認證Authenticate your credentials

  1. 新增下列 using 陳述式至主要類別檔 (預設為 Program.cs)。Add the following using statements to the main class file (which is Program.cs by default).

    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;
    
    using Microsoft.Azure.CognitiveServices.Language.TextAnalytics;
    using Microsoft.Azure.CognitiveServices.Language.TextAnalytics.Models;
    using Microsoft.Rest;
    
  2. 建立新的 ApiKeyServiceClientCredentials 類別以儲存認證,並對每個要求新增認證。Create a new ApiKeyServiceClientCredentials class to store the credentials and add them for each request.

    /// <summary>
    /// Allows authentication to the API by using a basic apiKey mechanism
    /// </summary>
    class ApiKeyServiceClientCredentials : ServiceClientCredentials
    {
        private readonly string subscriptionKey;
    
        /// <summary>
        /// Creates a new instance of the ApiKeyServiceClientCredentails class
        /// </summary>
        /// <param name="subscriptionKey">The subscription key to authenticate and authorize as</param>
        public ApiKeyServiceClientCredentials(string subscriptionKey)
        {
            this.subscriptionKey = subscriptionKey;
        }
    
        /// <summary>
        /// Add the Basic Authentication Header to each outgoing request
        /// </summary>
        /// <param name="request">The outgoing request</param>
        /// <param name="cancellationToken">A token to cancel the operation</param>
        public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
    
            request.Headers.Add("Ocp-Apim-Subscription-Key", this.subscriptionKey);
            return base.ProcessHttpRequestAsync(request, cancellationToken);
        }
    }
    
  3. 更新 Program 類別。Update the Program class. 新增文字分析訂用帳戶金鑰的常數成員,並新增另一個服務端點常數成員。Add a constant member for your Text Analytics subscription key, and another for the service endpoint. 請記得文字分析訂用帳戶要使用正確的 Azure 區域。Remember to use the correct Azure region for your Text Analytics subscription.

    private const string SubscriptionKey = "enter-your-key-here";
    
    private const string Endpoint = "enter-your-service-endpoint-here"; // For example: "https://westus.api.cognitive.microsoft.com";
    

提示

為了提升生產系統中的祕密安全性,建議使用 Azure Key VaultTo boost the security of secrets in production systems, we recommend that you use Azure Key Vault.

建立文字分析用戶端Create a Text Analytics client

在專案的 Main 函式中,呼叫您要叫用的範例方法。In the Main function of your project, call the sample method that you want to invoke. 傳遞您定義的 EndpointSubscriptionKey 參數。Pass the Endpoint and SubscriptionKey parameters that you defined.

    public static void Main(string[] args)
    {
        var credentials = new ApiKeyServiceClientCredentials(SubscriptionKey);
        var client = new TextAnalyticsClient(credentials)
        {
            Endpoint = Endpoint
        };

        // Change the console encoding to display non-ASCII characters.
        Console.OutputEncoding = System.Text.Encoding.UTF8;
        SentimentAnalysisExample(client).Wait();
        // DetectLanguageExample(client).Wait();
        // RecognizeEntitiesExample(client).Wait();
        // KeyPhraseExtractionExample(client).Wait();
        Console.ReadLine();
    }

下列各節將說明如何呼叫每個服務功能。The following sections describe how to call each service feature.

執行人氣分析Perform sentiment analysis

  1. 建立新函式 SentimentAnalysisExample(),以取用稍早建立的用戶端。Create a new function SentimentAnalysisExample() that takes the client that you created earlier.

  2. 產生 MultiLanguageInput 物件清單,其中包含您要分析的文件。Generate a list of MultiLanguageInput objects that contains the documents that you want to analyze.

    public static async Task SentimentAnalysisExample(TextAnalyticsClient client)
    {
        // The documents to be analyzed. Add the language of the document. The ID can be any value.
        var inputDocuments = new MultiLanguageBatchInput(
            new List<MultiLanguageInput>
            {
                new MultiLanguageInput("en", "1", "I had the best day of my life."),
                new MultiLanguageInput("en", "2", "This was a waste of my time. The speaker put me to sleep."),
                new MultiLanguageInput("es", "3", "No tengo dinero ni nada que dar..."),
                new MultiLanguageInput("it", "4", "L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."),
            });
        //...
    }
    
  3. 在同一個函式中,呼叫 client.SentimentAsync() 並取得結果。In the same function, call client.SentimentAsync() and get the result. 然後逐一查看結果。Then iterate through the results. 輸出每個文件的識別碼和人氣分數。Print each document's ID and sentiment score. 接近 0 的分數表示負面人氣,而接近 1 的分數則表示正面人氣。A score that's close to 0 indicates a negative sentiment, while a score that's closer to 1 indicates a positive sentiment.

    var result = await client.SentimentAsync(false, inputDocuments);
    
    // Printing sentiment results
    foreach (var document in result.Documents)
    {
        Console.WriteLine($"Document ID: {document.Id} , Sentiment Score: {document.Score:0.00}");
    }
    

輸出Output

Document ID: 1 , Sentiment Score: 0.87
Document ID: 2 , Sentiment Score: 0.11
Document ID: 3 , Sentiment Score: 0.44
Document ID: 4 , Sentiment Score: 1.00

執行語言偵測Perform language detection

  1. 建立新函式 DetectLanguageExample(),以取用稍早建立的用戶端。Create a new function DetectLanguageExample() that takes the client that you created earlier.

  2. 產生包含您文件的 LanguageInput 物件清單。Generate a list of LanguageInput objects that contains your documents.

    public static async Task DetectLanguageExample(TextAnalyticsClient client)
    {
    
        // The documents to be submitted for language detection. The ID can be any value.
        var inputDocuments = new LanguageBatchInput(
                new List<LanguageInput>
                    {
                        new LanguageInput(id: "1", text: "This is a document written in English."),
                        new LanguageInput(id: "2", text: "Este es un document escrito en Español."),
                        new LanguageInput(id: "3", text: "这是一个用中文写的文件")
                    });
        //...
    }
    
  3. 在同一個函式中,呼叫 client.DetectLanguageAsync() 並取得結果。In the same function, call client.DetectLanguageAsync() and get the result. 然後逐一查看結果。Then iterate through the results. 輸出每個文件的識別碼以及第一個傳回的語言。Print each document's ID and the first returned language.

    var langResults = await client.DetectLanguageAsync(false, inputDocuments);
    
    // Printing detected languages
    foreach (var document in langResults.Documents)
    {
        Console.WriteLine($"Document ID: {document.Id} , Language: {document.DetectedLanguages[0].Name}");
    }
    

輸出Output

===== LANGUAGE EXTRACTION ======
Document ID: 1 , Language: English
Document ID: 2 , Language: Spanish
Document ID: 3 , Language: Chinese_Simplified

執行實體辨識Perform entity recognition

  1. 建立新函式 RecognizeEntitiesExample(),以取用稍早建立的用戶端。Create a new function RecognizeEntitiesExample() that takes the client that you created earlier.

  2. 產生包含您文件的 MultiLanguageBatchInput 物件清單。Generate a list of MultiLanguageBatchInput objects that contains your documents.

    public static async Task RecognizeEntitiesExample(TextAnalyticsClient client)
    {
    
        // The documents to be submitted for entity recognition. The ID can be any value.
        var inputDocuments = new MultiLanguageBatchInput(
            new List<MultiLanguageInput>
            {
                new MultiLanguageInput("en", "1", "Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800."),
                new MultiLanguageInput("es", "2", "La sede principal de Microsoft se encuentra en la ciudad de Redmond, a 21 kilómetros de Seattle.")
            });
        //...
    }
    
  3. 在同一個函式中,呼叫 client.EntitiesAsync() 並取得結果。In the same function, call client.EntitiesAsync() and get the result. 然後逐一查看結果。Then iterate through the results. 輸出每個文件的識別碼。Print each document's ID. 對於每個偵測到的實體,輸出其維基百科名稱、類型和子類型 (如果存在) 以及原始文字中的位置。For each detected entity, print its Wikipedia name and the type and subtypes (if they exist) as well as the locations in the original text.

    var entitiesResult = await client.EntitiesAsync(false, inputDocuments);
    
    // Printing recognized entities
    foreach (var document in entitiesResult.Documents)
    {
        Console.WriteLine($"Document ID: {document.Id} ");
    
        Console.WriteLine("\t Entities:");
        foreach (var entity in document.Entities)
        {
            Console.WriteLine($"\t\tName: {entity.Name},\tType: {entity.Type ?? "N/A"},\tSub-Type: {entity.SubType ?? "N/A"}");
            foreach (var match in entity.Matches)
            {
                Console.WriteLine($"\t\t\tOffset: {match.Offset},\tLength: {match.Length},\tScore: {match.EntityTypeScore:F3}");
            }
        }
    }
    

輸出Output

Document ID: 1
         Entities:
                Name: Microsoft,        Type: Organization,     Sub-Type: N/A
                        Offset: 0,      Length: 9,      Score: 1.000
                Name: Bill Gates,       Type: Person,   Sub-Type: N/A
                        Offset: 25,     Length: 10,     Score: 1.000
                Name: Paul Allen,       Type: Person,   Sub-Type: N/A
                        Offset: 40,     Length: 10,     Score: 0.999
                Name: April 4,  Type: Other,    Sub-Type: N/A
                        Offset: 54,     Length: 7,      Score: 0.800
                Name: April 4, 1975,    Type: DateTime, Sub-Type: Date
                        Offset: 54,     Length: 13,     Score: 0.800
                Name: BASIC,    Type: Other,    Sub-Type: N/A
                        Offset: 89,     Length: 5,      Score: 0.800
                Name: Altair 8800,      Type: Other,    Sub-Type: N/A
                        Offset: 116,    Length: 11,     Score: 0.800
Document ID: 2
         Entities:
                Name: Microsoft,        Type: Organization,     Sub-Type: N/A
                        Offset: 21,     Length: 9,      Score: 1.000
                Name: Redmond (Washington),     Type: Location, Sub-Type: N/A
                        Offset: 60,     Length: 7,      Score: 0.991
                Name: 21 kilómetros,    Type: Quantity, Sub-Type: Dimension
                        Offset: 71,     Length: 13,     Score: 0.800
                Name: Seattle,  Type: Location, Sub-Type: N/A
                        Offset: 88,     Length: 7,      Score: 1.000

執行關鍵片語擷取Perform key phrase extraction

  1. 建立新函式 KeyPhraseExtractionExample(),以取用稍早建立的用戶端。Create a new function KeyPhraseExtractionExample() that takes the client that you created earlier.

  2. 產生包含您文件的 MultiLanguageBatchInput 物件清單。Generate a list of MultiLanguageBatchInput objects that contains your documents.

    public static async Task KeyPhraseExtractionExample(TextAnalyticsClient client)
    {
        var inputDocuments = new MultiLanguageBatchInput(
                    new List<MultiLanguageInput>
                    {
                        new MultiLanguageInput("ja", "1", "猫は幸せ"),
                        new MultiLanguageInput("de", "2", "Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
                        new MultiLanguageInput("en", "3", "My cat might need to see a veterinarian."),
                        new MultiLanguageInput("es", "4", "A mi me encanta el fútbol!")
                    });
        //...
    }
    
  3. 在同一個函式中,呼叫 client.KeyPhrasesAsync() 並取得結果。In the same function, call client.KeyPhrasesAsync() and get the result. 然後逐一查看結果。Then iterate through the results. 輸出每個文件的識別碼,以及任何偵測到的關鍵片語。Print each document's ID and any detected key phrases.

    var kpResults = await client.KeyPhrasesAsync(false, inputDocuments);
    
    // Printing keyphrases
    foreach (var document in kpResults.Documents)
    {
        Console.WriteLine($"Document ID: {document.Id} ");
    
        Console.WriteLine("\t Key phrases:");
    
        foreach (string keyphrase in document.KeyPhrases)
        {
            Console.WriteLine($"\t\t{keyphrase}");
        }
    }
    

輸出Output

Document ID: 1
         Key phrases:
                幸せ
Document ID: 2
         Key phrases:
                Stuttgart
                Hotel
                Fahrt
                Fu
Document ID: 3
         Key phrases:
                cat
                veterinarian
Document ID: 4
         Key phrases:
                fútbol

後續步驟Next steps