快速入门:使用适用于 Go 文本分析客户端库Quickstart: Use the Text Analytics client library for Go

备注

本快速入门仅适用于文本分析 2.1 版。This quickstart only applies to Text Analytics version 2.1. 目前,适用于 Go 的 v3 客户端库不可用。Currently, a v3 client library for Go is unavailable.

先决条件Prerequisites

  • Azure 订阅 - 创建试用订阅An Azure subscription - create one for trial
  • 最新版本的 GoThe latest version of Go
  • 你有了 Azure 订阅后,将在 Azure 门户中创建文本分析资源 ,以获取你的密钥和终结点。Once you have your Azure subscription, create a Text Analytics resource in the Azure portal to get your key and endpoint.
    • 你需要从创建的资源获取密钥和终结点,以便将应用程序连接到文本分析 API。You will need the key and endpoint from the resource you create to connect your application to the Text Analytics API. 稍后会在本快速入门中执行此操作。You'll do this later in the quickstart.
    • 可以使用免费定价层试用该服务,然后再升级到付费层进行生产。You can use the free pricing tier to try the service, and upgrade later to a paid tier for production.

设置Setting up

创建新的 Go 项目Create a new Go project

在控制台窗口(cmd、PowerShell、终端、Bash)中,为 Go 项目创建一个新的工作区并导航到该工作区。In a console window (cmd, PowerShell, Terminal, Bash), create a new workspace for your Go project and navigate to it. 工作区包含三个文件夹:Your workspace will contain three folders:

  • src - 此目录包含源代码和包。src - This directory contains source code and packages. 使用 go get 命令安装的任何包将位于此处。Any packages installed with the go get command will reside here.
  • pkg - 此目录包含编译的 Go 包对象。pkg - This directory contains the compiled Go package objects. 这些文件使用 .a 扩展名。These files all have an .a extension.
  • bin - 此目录包含运行 go install 时创建的二进制可执行文件。bin - This directory contains the binary executable files that are created when you run go install.

提示

详细了解 Go 工作区的结构。Learn more about the structure of a Go workspace. 本指南包含有关设置 $GOPATH$GOROOT 的信息。This guide includes information for setting $GOPATH and $GOROOT.

创建名为 my-app 的工作区,并为 srcpkgbin 创建所需的子目录:Create a workspace called my-app and the required sub directories for src, pkg, and bin:

$ mkdir -p my-app/{src, bin, pkg}  
$ cd my-app

安装适用于 Go 的文本分析客户端库Install the Text Analytics client library for Go

安装适用于 Go 的客户端库:Install the client library for Go:

$ go get -u <https://github.com/Azure/azure-sdk-for-go/tree/master/services/cognitiveservices/v2.1/textanalytics>

或者,如果使用 dep,则在存储库中运行:or if you use dep, within your repo run:

$ dep ensure -add <https://github.com/Azure/azure-sdk-for-go/tree/master/services/cognitiveservices/v2.1/textanalytics>

创建 Go 应用程序Create your Go application

接下来,创建名为 src/quickstart.go 的文件:Next, create a file named src/quickstart.go:

$ cd src
$ touch quickstart.go

在喜好的 IDE 或文本编辑器中打开 quickstart.goOpen quickstart.go in your favorite IDE or text editor. 然后添加包名称并导入以下库:Then add the package name and import the following libraries:

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

package cognitiveservices
// <imports>
import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "os"

    "github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v2.1/textanalytics"
    "github.com/Azure/go-autorest/autorest"
    "github.com/Azure/go-autorest/autorest/to"
)
// </imports>

// <client>
func GetTextAnalyticsClient() textanalytics.BaseClient {
    subscriptionKeyVar := "TEXT_ANALYTICS_SUBSCRIPTION_KEY"
    if "" == os.Getenv(subscriptionKeyVar) {
        log.Fatal("Please set/export the environment variable " + subscriptionKeyVar + ".")
    }
    subscriptionKey := os.Getenv(subscriptionKeyVar)
    endpointVar := "TEXT_ANALYTICS_ENDPOINT"
    if "" == os.Getenv(endpointVar) {
        log.Fatal("Please set/export the environment variable " + endpointVar + ".")
    }
    endpoint := os.Getenv(endpointVar)

    textAnalyticsClient := textanalytics.New(endpoint)
    textAnalyticsClient.Authorizer = autorest.NewCognitiveServicesAuthorizer(subscriptionKey)

    return textAnalyticsClient
}
// </client>

// detects the sentiment of a set of text records
// <sentimentAnalysis>
func SentimentAnalysis() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("I had the best day of my life."),
        },
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("This was a waste of my time. The speaker put me to sleep."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("2"),
            Text:     to.StringPtr("No tengo dinero ni nada que dar..."),
        },
        {
            Language: to.StringPtr("it"),
            ID:       to.StringPtr("3"),
            Text:     to.StringPtr("L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.Sentiment(ctx, to.BoolPtr(false), &batchInput)
    var batchResult textanalytics.SentimentBatchResult
    jsonString, _ := json.Marshal(result)
    _ = json.Unmarshal(jsonString, &batchResult)

    // Printing sentiment results
    for _, document := range *batchResult.Documents {
        fmt.Printf("Document ID: %s ", *document.ID)
        fmt.Printf("Sentiment Score: %f\n", *document.Score)
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *batchResult.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </sentimentAnalysis>

//detects the language of a text document
// <languageDetection>
func DetectLanguage() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.LanguageInput{
        {
            ID:   to.StringPtr("0"),
            Text: to.StringPtr("This is a document written in English."),
        },
        {
            ID:   to.StringPtr("1"),
            Text: to.StringPtr("Este es un document escrito en Español."),
        },
        {
            ID:   to.StringPtr("2"),
            Text: to.StringPtr("这是一个用中文写的文件"),
        },
    }

    batchInput := textanalytics.LanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.DetectLanguage(ctx, to.BoolPtr(false), &batchInput)

    // Printing language detection results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s ", *document.ID)
        fmt.Printf("Detected Languages with Score: ")
        for _, language := range *document.DetectedLanguages {
            fmt.Printf("%s %f,", *language.Name, *language.Score)
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </languageDetection>

// extracts key-phrases from a text document
// <keyPhrases>
func ExtractKeyPhrases() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("ja"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("猫は幸せ"),
        },
        {
            Language: to.StringPtr("de"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
        },
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("2"),
            Text:     to.StringPtr("My cat might need to see a veterinarian."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("3"),
            Text:     to.StringPtr("A mi me encanta el fútbol!"),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.KeyPhrases(ctx, to.BoolPtr(false), &batchInput)

    // Printing extracted key phrases results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s\n", *document.ID)
        fmt.Printf("\tExtracted Key Phrases:\n")
        for _, keyPhrase := range *document.KeyPhrases {
            fmt.Printf("\t\t%s\n", keyPhrase)
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </keyPhrases>

//  identifies well-known entities in a text document
// <entityRecognition>
func ExtractEntities() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("La sede principal de Microsoft se encuentra en la ciudad de Redmond, a 21 kilómetros de Seattle."),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.Entities(ctx, to.BoolPtr(false), &batchInput)

    // Printing extracted entities results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s\n", *document.ID)
        fmt.Printf("\tExtracted Entities:\n")
        for _, entity := range *document.Entities {
            fmt.Printf("\t\tName: %s\tType: %s", *entity.Name, *entity.Type)
            if entity.SubType != nil {
                fmt.Printf("\tSub-Type: %s\n", *entity.SubType)
            }
            fmt.Println()
            for _, match := range *entity.Matches {
                fmt.Printf("\t\t\tOffset: %v\tLength: %v\tScore: %f\n", *match.Offset, *match.Length, *match.EntityTypeScore)
            }
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </entityRecognition>

对象模型Object model

文本分析客户端是一个 BaseClient 对象,它使用你的密钥向 Azure 进行身份验证。The Text Analytics client is a BaseClient object that authenticates to Azure using your key. 该客户端提供了几种方法来分析文本,文本可以是单个字符串,也可以是批处理。The client provides several methods for analyzing text, as a single string, or a batch.

文本将以 documents 的列表的形式发送到 API,该项是包含 idtextlanguage 属性的组合的 dictionary 对象,具体取决于所用的方法。Text is sent to the API as a list of documents, which are dictionary objects containing a combination of id, text, and language attributes depending on the method used. text 属性存储要以源 language 分析的文本,而 id 则可以是任何值。The text attribute stores the text to be analyzed in the origin language, and the id can be any value.

响应对象是一个列表,其中包含每个文档的分析信息。The response object is a list containing the analysis information for each document.

代码示例Code examples

这些代码片段演示如何使用适用于 Go 的文本分析客户端库执行以下操作:These code snippets show you how to do the following with the Text Analytics client library for Go:

验证客户端Authenticate the client

在新函数中,为资源的 Azure 终结点和订阅密钥创建变量。In a new function, create variables for your resource's Azure endpoint and subscription key.

重要

转到 Azure 门户。Go to the Azure portal. 如果在“先决条件”部分中创建的文本分析资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。If the Text Analytics resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. 在资源的“密钥和终结点”页的“资源管理”下可以找到密钥和终结点 。You can find your key and endpoint in the resource's key and endpoint page, under resource management.

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。Remember to remove the key from your code when you're done, and never post it publicly. 对于生产环境,请考虑使用安全的方法来存储和访问凭据。For production, consider using a secure way of storing and accessing your credentials. 例如,Azure 密钥保管库For example, Azure key vault.

创建新的 BaseClient 对象。Create a new BaseClient object. 将密钥传递给 autorest.NewCognitiveServicesAuthorizer() 函数,随后它将传递给客户端的 authorizer 属性。Pass your key to the autorest.NewCognitiveServicesAuthorizer() function, which will then be passed to the client's authorizer property.

func GetTextAnalyticsClient() textanalytics.BaseClient {
    var key string = "<paste-your-text-analytics-key-here>"
    var endpoint string = "<paste-your-text-analytics-endpoint-here>"

    textAnalyticsClient := textanalytics.New(endpoint)
    textAnalyticsClient.Authorizer = autorest.NewCognitiveServicesAuthorizer(key)

    return textAnalyticsClient
}

情绪分析Sentiment analysis

创建名为 SentimentAnalysis() 的新函数,并使用先前创建的 GetTextAnalyticsClient() 方法创建客户端。Create a new function called SentimentAnalysis() and create a client using the GetTextAnalyticsClient() method created earlier. 创建 MultiLanguageInput 对象的列表,其中包含要分析的文档。Create a list of MultiLanguageInput objects, containing the documents you want to analyze. 每个对象会包含 idLanguagetext 属性。Each object will contain an id, Language and a text attribute. text 属性存储要分析的文本,language 是文档的语言,id 则可以是任何值。The text attribute stores the text to be analyzed, language is the language of the document, and the id can be any value.

调用客户端的 Sentiment() 函数并获取结果。Call the client's Sentiment() function and get the result. 然后循环访问结果,输出每个文档的 ID 和情绪分数。Then iterate through the results, and print each document's ID, and sentiment score. 评分接近 0 表示消极情绪,评分接近 1 表示积极情绪。A score closer to 0 indicates a negative sentiment, while a score closer to 1 indicates a positive sentiment.

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

package cognitiveservices
// <imports>
import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "os"

    "github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v2.1/textanalytics"
    "github.com/Azure/go-autorest/autorest"
    "github.com/Azure/go-autorest/autorest/to"
)
// </imports>

// <client>
func GetTextAnalyticsClient() textanalytics.BaseClient {
    subscriptionKeyVar := "TEXT_ANALYTICS_SUBSCRIPTION_KEY"
    if "" == os.Getenv(subscriptionKeyVar) {
        log.Fatal("Please set/export the environment variable " + subscriptionKeyVar + ".")
    }
    subscriptionKey := os.Getenv(subscriptionKeyVar)
    endpointVar := "TEXT_ANALYTICS_ENDPOINT"
    if "" == os.Getenv(endpointVar) {
        log.Fatal("Please set/export the environment variable " + endpointVar + ".")
    }
    endpoint := os.Getenv(endpointVar)

    textAnalyticsClient := textanalytics.New(endpoint)
    textAnalyticsClient.Authorizer = autorest.NewCognitiveServicesAuthorizer(subscriptionKey)

    return textAnalyticsClient
}
// </client>

// detects the sentiment of a set of text records
// <sentimentAnalysis>
func SentimentAnalysis() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("I had the best day of my life."),
        },
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("This was a waste of my time. The speaker put me to sleep."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("2"),
            Text:     to.StringPtr("No tengo dinero ni nada que dar..."),
        },
        {
            Language: to.StringPtr("it"),
            ID:       to.StringPtr("3"),
            Text:     to.StringPtr("L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.Sentiment(ctx, to.BoolPtr(false), &batchInput)
    var batchResult textanalytics.SentimentBatchResult
    jsonString, _ := json.Marshal(result)
    _ = json.Unmarshal(jsonString, &batchResult)

    // Printing sentiment results
    for _, document := range *batchResult.Documents {
        fmt.Printf("Document ID: %s ", *document.ID)
        fmt.Printf("Sentiment Score: %f\n", *document.Score)
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *batchResult.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </sentimentAnalysis>

//detects the language of a text document
// <languageDetection>
func DetectLanguage() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.LanguageInput{
        {
            ID:   to.StringPtr("0"),
            Text: to.StringPtr("This is a document written in English."),
        },
        {
            ID:   to.StringPtr("1"),
            Text: to.StringPtr("Este es un document escrito en Español."),
        },
        {
            ID:   to.StringPtr("2"),
            Text: to.StringPtr("这是一个用中文写的文件"),
        },
    }

    batchInput := textanalytics.LanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.DetectLanguage(ctx, to.BoolPtr(false), &batchInput)

    // Printing language detection results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s ", *document.ID)
        fmt.Printf("Detected Languages with Score: ")
        for _, language := range *document.DetectedLanguages {
            fmt.Printf("%s %f,", *language.Name, *language.Score)
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </languageDetection>

// extracts key-phrases from a text document
// <keyPhrases>
func ExtractKeyPhrases() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("ja"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("猫は幸せ"),
        },
        {
            Language: to.StringPtr("de"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
        },
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("2"),
            Text:     to.StringPtr("My cat might need to see a veterinarian."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("3"),
            Text:     to.StringPtr("A mi me encanta el fútbol!"),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.KeyPhrases(ctx, to.BoolPtr(false), &batchInput)

    // Printing extracted key phrases results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s\n", *document.ID)
        fmt.Printf("\tExtracted Key Phrases:\n")
        for _, keyPhrase := range *document.KeyPhrases {
            fmt.Printf("\t\t%s\n", keyPhrase)
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </keyPhrases>

//  identifies well-known entities in a text document
// <entityRecognition>
func ExtractEntities() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("La sede principal de Microsoft se encuentra en la ciudad de Redmond, a 21 kilómetros de Seattle."),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.Entities(ctx, to.BoolPtr(false), &batchInput)

    // Printing extracted entities results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s\n", *document.ID)
        fmt.Printf("\tExtracted Entities:\n")
        for _, entity := range *document.Entities {
            fmt.Printf("\t\tName: %s\tType: %s", *entity.Name, *entity.Type)
            if entity.SubType != nil {
                fmt.Printf("\tSub-Type: %s\n", *entity.SubType)
            }
            fmt.Println()
            for _, match := range *entity.Matches {
                fmt.Printf("\t\t\tOffset: %v\tLength: %v\tScore: %f\n", *match.Offset, *match.Length, *match.EntityTypeScore)
            }
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </entityRecognition>

在项目中调用 SentimentAnalysis()call SentimentAnalysis() in your project.

输出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

语言检测Language detection

创建名为 LanguageDetection() 的新函数,并使用先前创建的 GetTextAnalyticsClient() 方法创建客户端。Create a new function called LanguageDetection() and create a client using the GetTextAnalyticsClient() method created earlier. 创建 LanguageInput 对象的列表,其中包含要分析的文档。Create a list of LanguageInput objects, containing the documents you want to analyze. 每个对象会包含 idtext 属性。Each object will contain an id and a text attribute. text 属性存储要分析的文本,而 id 则可以是任何值。The text attribute stores the text to be analyzed, and the id can be any value.

调用客户端的 DetectLanguage() 并获取结果。Call the client's DetectLanguage() and get the result. 然后循环访问结果,输出每个文档的 ID 和检测到的语言。Then iterate through the results, and print each document's ID, and detected language.

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

package cognitiveservices
// <imports>
import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "os"

    "github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v2.1/textanalytics"
    "github.com/Azure/go-autorest/autorest"
    "github.com/Azure/go-autorest/autorest/to"
)
// </imports>

// <client>
func GetTextAnalyticsClient() textanalytics.BaseClient {
    subscriptionKeyVar := "TEXT_ANALYTICS_SUBSCRIPTION_KEY"
    if "" == os.Getenv(subscriptionKeyVar) {
        log.Fatal("Please set/export the environment variable " + subscriptionKeyVar + ".")
    }
    subscriptionKey := os.Getenv(subscriptionKeyVar)
    endpointVar := "TEXT_ANALYTICS_ENDPOINT"
    if "" == os.Getenv(endpointVar) {
        log.Fatal("Please set/export the environment variable " + endpointVar + ".")
    }
    endpoint := os.Getenv(endpointVar)

    textAnalyticsClient := textanalytics.New(endpoint)
    textAnalyticsClient.Authorizer = autorest.NewCognitiveServicesAuthorizer(subscriptionKey)

    return textAnalyticsClient
}
// </client>

// detects the sentiment of a set of text records
// <sentimentAnalysis>
func SentimentAnalysis() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("I had the best day of my life."),
        },
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("This was a waste of my time. The speaker put me to sleep."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("2"),
            Text:     to.StringPtr("No tengo dinero ni nada que dar..."),
        },
        {
            Language: to.StringPtr("it"),
            ID:       to.StringPtr("3"),
            Text:     to.StringPtr("L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.Sentiment(ctx, to.BoolPtr(false), &batchInput)
    var batchResult textanalytics.SentimentBatchResult
    jsonString, _ := json.Marshal(result)
    _ = json.Unmarshal(jsonString, &batchResult)

    // Printing sentiment results
    for _, document := range *batchResult.Documents {
        fmt.Printf("Document ID: %s ", *document.ID)
        fmt.Printf("Sentiment Score: %f\n", *document.Score)
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *batchResult.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </sentimentAnalysis>

//detects the language of a text document
// <languageDetection>
func DetectLanguage() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.LanguageInput{
        {
            ID:   to.StringPtr("0"),
            Text: to.StringPtr("This is a document written in English."),
        },
        {
            ID:   to.StringPtr("1"),
            Text: to.StringPtr("Este es un document escrito en Español."),
        },
        {
            ID:   to.StringPtr("2"),
            Text: to.StringPtr("这是一个用中文写的文件"),
        },
    }

    batchInput := textanalytics.LanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.DetectLanguage(ctx, to.BoolPtr(false), &batchInput)

    // Printing language detection results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s ", *document.ID)
        fmt.Printf("Detected Languages with Score: ")
        for _, language := range *document.DetectedLanguages {
            fmt.Printf("%s %f,", *language.Name, *language.Score)
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </languageDetection>

// extracts key-phrases from a text document
// <keyPhrases>
func ExtractKeyPhrases() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("ja"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("猫は幸せ"),
        },
        {
            Language: to.StringPtr("de"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
        },
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("2"),
            Text:     to.StringPtr("My cat might need to see a veterinarian."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("3"),
            Text:     to.StringPtr("A mi me encanta el fútbol!"),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.KeyPhrases(ctx, to.BoolPtr(false), &batchInput)

    // Printing extracted key phrases results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s\n", *document.ID)
        fmt.Printf("\tExtracted Key Phrases:\n")
        for _, keyPhrase := range *document.KeyPhrases {
            fmt.Printf("\t\t%s\n", keyPhrase)
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </keyPhrases>

//  identifies well-known entities in a text document
// <entityRecognition>
func ExtractEntities() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("La sede principal de Microsoft se encuentra en la ciudad de Redmond, a 21 kilómetros de Seattle."),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.Entities(ctx, to.BoolPtr(false), &batchInput)

    // Printing extracted entities results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s\n", *document.ID)
        fmt.Printf("\tExtracted Entities:\n")
        for _, entity := range *document.Entities {
            fmt.Printf("\t\tName: %s\tType: %s", *entity.Name, *entity.Type)
            if entity.SubType != nil {
                fmt.Printf("\tSub-Type: %s\n", *entity.SubType)
            }
            fmt.Println()
            for _, match := range *entity.Matches {
                fmt.Printf("\t\t\tOffset: %v\tLength: %v\tScore: %f\n", *match.Offset, *match.Length, *match.EntityTypeScore)
            }
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </entityRecognition>

在项目中调用 LanguageDetection()Call LanguageDetection() in your project.

输出Output

Document ID: 0 , Language: English 
Document ID: 1 , Language: Spanish
Document ID: 2 , Language: Chinese_Simplified

实体识别Entity recognition

创建名为 ExtractEntities() 的新函数,并使用先前创建的 GetTextAnalyticsClient() 方法创建客户端。Create a new function called ExtractEntities() and create a client using the GetTextAnalyticsClient() method created earlier. 创建 MultiLanguageInput 对象的列表,其中包含要分析的文档。Create a list of MultiLanguageInput objects, containing the documents you want to analyze. 每个对象会包含 idlanguagetext 属性。Each object will contain an id, language, and a text attribute. text 属性存储要分析的文本,language 是文档的语言,id 则可以是任何值。The text attribute stores the text to be analyzed, language is the language of the document, and the id can be any value.

调用客户端的 Entities() 并获取结果。Call the client's Entities() and get the result. 然后循环访问结果,输出每个文档的 ID 和提取的实体分数。Then iterate through the results, and print each document's ID, and extracted entities score.

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

package cognitiveservices
// <imports>
import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "os"

    "github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v2.1/textanalytics"
    "github.com/Azure/go-autorest/autorest"
    "github.com/Azure/go-autorest/autorest/to"
)
// </imports>

// <client>
func GetTextAnalyticsClient() textanalytics.BaseClient {
    subscriptionKeyVar := "TEXT_ANALYTICS_SUBSCRIPTION_KEY"
    if "" == os.Getenv(subscriptionKeyVar) {
        log.Fatal("Please set/export the environment variable " + subscriptionKeyVar + ".")
    }
    subscriptionKey := os.Getenv(subscriptionKeyVar)
    endpointVar := "TEXT_ANALYTICS_ENDPOINT"
    if "" == os.Getenv(endpointVar) {
        log.Fatal("Please set/export the environment variable " + endpointVar + ".")
    }
    endpoint := os.Getenv(endpointVar)

    textAnalyticsClient := textanalytics.New(endpoint)
    textAnalyticsClient.Authorizer = autorest.NewCognitiveServicesAuthorizer(subscriptionKey)

    return textAnalyticsClient
}
// </client>

// detects the sentiment of a set of text records
// <sentimentAnalysis>
func SentimentAnalysis() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("I had the best day of my life."),
        },
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("This was a waste of my time. The speaker put me to sleep."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("2"),
            Text:     to.StringPtr("No tengo dinero ni nada que dar..."),
        },
        {
            Language: to.StringPtr("it"),
            ID:       to.StringPtr("3"),
            Text:     to.StringPtr("L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.Sentiment(ctx, to.BoolPtr(false), &batchInput)
    var batchResult textanalytics.SentimentBatchResult
    jsonString, _ := json.Marshal(result)
    _ = json.Unmarshal(jsonString, &batchResult)

    // Printing sentiment results
    for _, document := range *batchResult.Documents {
        fmt.Printf("Document ID: %s ", *document.ID)
        fmt.Printf("Sentiment Score: %f\n", *document.Score)
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *batchResult.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </sentimentAnalysis>

//detects the language of a text document
// <languageDetection>
func DetectLanguage() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.LanguageInput{
        {
            ID:   to.StringPtr("0"),
            Text: to.StringPtr("This is a document written in English."),
        },
        {
            ID:   to.StringPtr("1"),
            Text: to.StringPtr("Este es un document escrito en Español."),
        },
        {
            ID:   to.StringPtr("2"),
            Text: to.StringPtr("这是一个用中文写的文件"),
        },
    }

    batchInput := textanalytics.LanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.DetectLanguage(ctx, to.BoolPtr(false), &batchInput)

    // Printing language detection results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s ", *document.ID)
        fmt.Printf("Detected Languages with Score: ")
        for _, language := range *document.DetectedLanguages {
            fmt.Printf("%s %f,", *language.Name, *language.Score)
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </languageDetection>

// extracts key-phrases from a text document
// <keyPhrases>
func ExtractKeyPhrases() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("ja"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("猫は幸せ"),
        },
        {
            Language: to.StringPtr("de"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
        },
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("2"),
            Text:     to.StringPtr("My cat might need to see a veterinarian."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("3"),
            Text:     to.StringPtr("A mi me encanta el fútbol!"),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.KeyPhrases(ctx, to.BoolPtr(false), &batchInput)

    // Printing extracted key phrases results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s\n", *document.ID)
        fmt.Printf("\tExtracted Key Phrases:\n")
        for _, keyPhrase := range *document.KeyPhrases {
            fmt.Printf("\t\t%s\n", keyPhrase)
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </keyPhrases>

//  identifies well-known entities in a text document
// <entityRecognition>
func ExtractEntities() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("La sede principal de Microsoft se encuentra en la ciudad de Redmond, a 21 kilómetros de Seattle."),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.Entities(ctx, to.BoolPtr(false), &batchInput)

    // Printing extracted entities results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s\n", *document.ID)
        fmt.Printf("\tExtracted Entities:\n")
        for _, entity := range *document.Entities {
            fmt.Printf("\t\tName: %s\tType: %s", *entity.Name, *entity.Type)
            if entity.SubType != nil {
                fmt.Printf("\tSub-Type: %s\n", *entity.SubType)
            }
            fmt.Println()
            for _, match := range *entity.Matches {
                fmt.Printf("\t\t\tOffset: %v\tLength: %v\tScore: %f\n", *match.Offset, *match.Length, *match.EntityTypeScore)
            }
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </entityRecognition>

在项目中调用 ExtractEntities()call ExtractEntities() in your project.

输出Output

Document ID: 1
    Name: Microsoft,        Type: Organization,     Sub-Type: N/A
    Offset: 0, Length: 9,   Score: 1.0
    Name: Bill Gates,       Type: Person,   Sub-Type: N/A
    Offset: 25, Length: 10, Score: 0.999847412109375
    Name: Paul Allen,       Type: Person,   Sub-Type: N/A
    Offset: 40, Length: 10, Score: 0.9988409876823425
    Name: April 4,  Type: Other,    Sub-Type: N/A
    Offset: 54, Length: 7,  Score: 0.8
    Name: April 4, 1975,    Type: DateTime, Sub-Type: Date
    Offset: 54, Length: 13, Score: 0.8
    Name: BASIC,    Type: Other,    Sub-Type: N/A
    Offset: 89, Length: 5,  Score: 0.8
    Name: Altair 8800,      Type: Other,    Sub-Type: N/A
    Offset: 116, Length: 11,        Score: 0.8

Document ID: 2
    Name: Microsoft,        Type: Organization,     Sub-Type: N/A
    Offset: 21, Length: 9,  Score: 0.999755859375
    Name: Redmond (Washington),     Type: Location, Sub-Type: N/A
    Offset: 60, Length: 7,  Score: 0.9911284446716309
    Name: 21 kilómetros,    Type: Quantity, Sub-Type: Dimension
    Offset: 71, Length: 13, Score: 0.8
    Name: Seattle,  Type: Location, Sub-Type: N/A
    Offset: 88, Length: 7,  Score: 0.9998779296875

关键短语提取Key phrase extraction

创建名为 ExtractKeyPhrases() 的新函数,并使用先前创建的 GetTextAnalyticsClient() 方法创建客户端。Create a new function called ExtractKeyPhrases() and create a client using the GetTextAnalyticsClient() method created earlier. 创建 MultiLanguageInput 对象的列表,其中包含要分析的文档。Create a list of MultiLanguageInput objects, containing the documents you want to analyze. 每个对象会包含 idlanguagetext 属性。Each object will contain an id, language, and a text attribute. text 属性存储要分析的文本,language 是文档的语言,id 则可以是任何值。The text attribute stores the text to be analyzed, language is the language of the document, and the id can be any value.

调用客户端的 KeyPhrases() 并获取结果。Call the client's KeyPhrases() and get the result. 然后循环访问结果,输出每个文档的 ID 以及提取的关键短语。Then iterate through the results, and print each document's ID, and extracted key phrases.

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

package cognitiveservices
// <imports>
import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "os"

    "github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v2.1/textanalytics"
    "github.com/Azure/go-autorest/autorest"
    "github.com/Azure/go-autorest/autorest/to"
)
// </imports>

// <client>
func GetTextAnalyticsClient() textanalytics.BaseClient {
    subscriptionKeyVar := "TEXT_ANALYTICS_SUBSCRIPTION_KEY"
    if "" == os.Getenv(subscriptionKeyVar) {
        log.Fatal("Please set/export the environment variable " + subscriptionKeyVar + ".")
    }
    subscriptionKey := os.Getenv(subscriptionKeyVar)
    endpointVar := "TEXT_ANALYTICS_ENDPOINT"
    if "" == os.Getenv(endpointVar) {
        log.Fatal("Please set/export the environment variable " + endpointVar + ".")
    }
    endpoint := os.Getenv(endpointVar)

    textAnalyticsClient := textanalytics.New(endpoint)
    textAnalyticsClient.Authorizer = autorest.NewCognitiveServicesAuthorizer(subscriptionKey)

    return textAnalyticsClient
}
// </client>

// detects the sentiment of a set of text records
// <sentimentAnalysis>
func SentimentAnalysis() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("I had the best day of my life."),
        },
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("This was a waste of my time. The speaker put me to sleep."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("2"),
            Text:     to.StringPtr("No tengo dinero ni nada que dar..."),
        },
        {
            Language: to.StringPtr("it"),
            ID:       to.StringPtr("3"),
            Text:     to.StringPtr("L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.Sentiment(ctx, to.BoolPtr(false), &batchInput)
    var batchResult textanalytics.SentimentBatchResult
    jsonString, _ := json.Marshal(result)
    _ = json.Unmarshal(jsonString, &batchResult)

    // Printing sentiment results
    for _, document := range *batchResult.Documents {
        fmt.Printf("Document ID: %s ", *document.ID)
        fmt.Printf("Sentiment Score: %f\n", *document.Score)
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *batchResult.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </sentimentAnalysis>

//detects the language of a text document
// <languageDetection>
func DetectLanguage() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.LanguageInput{
        {
            ID:   to.StringPtr("0"),
            Text: to.StringPtr("This is a document written in English."),
        },
        {
            ID:   to.StringPtr("1"),
            Text: to.StringPtr("Este es un document escrito en Español."),
        },
        {
            ID:   to.StringPtr("2"),
            Text: to.StringPtr("这是一个用中文写的文件"),
        },
    }

    batchInput := textanalytics.LanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.DetectLanguage(ctx, to.BoolPtr(false), &batchInput)

    // Printing language detection results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s ", *document.ID)
        fmt.Printf("Detected Languages with Score: ")
        for _, language := range *document.DetectedLanguages {
            fmt.Printf("%s %f,", *language.Name, *language.Score)
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </languageDetection>

// extracts key-phrases from a text document
// <keyPhrases>
func ExtractKeyPhrases() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("ja"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("猫は幸せ"),
        },
        {
            Language: to.StringPtr("de"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
        },
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("2"),
            Text:     to.StringPtr("My cat might need to see a veterinarian."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("3"),
            Text:     to.StringPtr("A mi me encanta el fútbol!"),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.KeyPhrases(ctx, to.BoolPtr(false), &batchInput)

    // Printing extracted key phrases results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s\n", *document.ID)
        fmt.Printf("\tExtracted Key Phrases:\n")
        for _, keyPhrase := range *document.KeyPhrases {
            fmt.Printf("\t\t%s\n", keyPhrase)
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </keyPhrases>

//  identifies well-known entities in a text document
// <entityRecognition>
func ExtractEntities() {
    textAnalyticsClient := GetTextAnalyticsClient()
    ctx := context.Background()
    inputDocuments := []textanalytics.MultiLanguageInput{
        {
            Language: to.StringPtr("en"),
            ID:       to.StringPtr("0"),
            Text:     to.StringPtr("Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800."),
        },
        {
            Language: to.StringPtr("es"),
            ID:       to.StringPtr("1"),
            Text:     to.StringPtr("La sede principal de Microsoft se encuentra en la ciudad de Redmond, a 21 kilómetros de Seattle."),
        },
    }

    batchInput := textanalytics.MultiLanguageBatchInput{Documents: &inputDocuments}
    result, _ := textAnalyticsClient.Entities(ctx, to.BoolPtr(false), &batchInput)

    // Printing extracted entities results
    for _, document := range *result.Documents {
        fmt.Printf("Document ID: %s\n", *document.ID)
        fmt.Printf("\tExtracted Entities:\n")
        for _, entity := range *document.Entities {
            fmt.Printf("\t\tName: %s\tType: %s", *entity.Name, *entity.Type)
            if entity.SubType != nil {
                fmt.Printf("\tSub-Type: %s\n", *entity.SubType)
            }
            fmt.Println()
            for _, match := range *entity.Matches {
                fmt.Printf("\t\t\tOffset: %v\tLength: %v\tScore: %f\n", *match.Offset, *match.Length, *match.EntityTypeScore)
            }
        }
        fmt.Println()
    }

    // Printing document errors
    fmt.Println("Document Errors")
    for _, err := range *result.Errors {
        fmt.Printf("Document ID: %s Message : %s\n", *err.ID, *err.Message)
    }
}
// </entityRecognition>

在项目中调用 ExtractKeyPhrases()Call ExtractKeyPhrases() in your project.

输出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