快速入门:使用 Go 调用文本分析认知服务Quickstart: Using Go to call the Text Analytics Cognitive Service

本文展示了如何将 文本分析 API 与 Go 配合使用来检测语言分析情绪提取关键短语以及识别链接的实体This article shows you how to detect language, analyze sentiment, extract key phrases, and identify linked entities using the Text Analytics APIs with Go.

有关 API 的技术文档,请参阅 API 定义Refer to the API definitions for technical documentation for the APIs.

先决条件Prerequisites

必须拥有可以访问文本分析 API 的认知服务 API 订阅You must have a Cognitive Services API subscription with access to the Text Analytics API. 如果没有订阅,可以创建一个 1 元试用帐户If you don't have a subscription, you can create a 1rmb trial account. 在继续操作之前,需使用激活帐户后由系统提供的文本分析订阅密钥。Before continuing, you will need the Text Analytics subscription key provided after activating your account.

还必须拥有在注册期间生成的终结点和访问密钥You must also have the endpoint and access key that was generated for you during sign-up.

检测语言Detect language

语言检测 API 使用检测语言方法检测文本文档的语言。The Language Detection API detects the language of a text document, using the Detect Language method.

  1. 在你喜欢使用的代码编辑器中新建一个 Go 项目。Create a new Go project in your favorite code editor.
  2. 添加以下提供的代码。Add the code provided below.
  3. subscriptionKey 值替换为对你的订阅有效的访问密钥。Replace the subscriptionKey value with an access key valid for your subscription.
  4. uriBase 中的位置(当前为 chinaeast2)替换为进行注册的区域。Replace the location in uriBase (currently chinaeast2) to the region you signed up for.
  5. 使用“.go”扩展名保存文件。Save the file with a '.go' extension.
  6. 从根文件夹中安装了 Go 的计算机上打开命令提示符。Open a command prompt on a computer with Go installed from your root folder.
  7. 生成文件,例如:go build detect.goBuild the file, for example: go build detect.go.
  8. 运行文件,例如:go run detect.goRun the file, for example: go run detect.go.
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
    "time"
)

func main() {
    // Replace the subscriptionKey string value with your valid subscription key
    const subscriptionKey = "<Subscription Key>"

    /*
    Replace or verify the region.

    You must use the same region in your REST API call as you used to obtain your access keys.
    For example, if you obtained your access keys from the chinanorth region, replace 
    "chinaeast2" in the URI below with "chinanorth".

    */
    const uriBase =    "https://chinaeast2.api.cognitive.azure.cn"
    const uriPath = "/text/analytics/v2.1/languages"

    const uri = uriBase + uriPath

    data := []map[string]string{
        {"id": "1", "text": "This is a document written in English."},
        {"id": "2", "text": "Este es un document escrito en Español."},
        {"id": "3", "text": "这是一个用中文写的文件"},
    }

    documents, err := json.Marshal(&data)
    if err != nil {
        fmt.Printf("Error marshaling data: %v\n", err)
        return
    }

    r := strings.NewReader("{\"documents\": " + string(documents) + "}")

    client := &http.Client{
        Timeout: time.Second * 2,
    }

    req, err := http.NewRequest("POST", uri, r)
    if err != nil {
        fmt.Printf("Error creating request: %v\n", err)
        return
    }

    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)

    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error on request: %v\n", err)
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("Error reading response body: %v\n", err)
        return
    }

    var f interface{}
    json.Unmarshal(body, &f)

    jsonFormatted, err := json.MarshalIndent(f, "", "  ")
    if err != nil {
        fmt.Printf("Error producing JSON: %v\n", err)
        return
    }
    fmt.Println(string(jsonFormatted))
}

检测语言响应Detect language response

在 JSON 中返回成功的响应,如以下示例所示:A successful response is returned in JSON, as shown in the following example:


{
   "documents": [
      {
         "id": "1",
         "detectedLanguages": [
            {
               "name": "English",
               "iso6391Name": "en",
               "score": 1.0
            }
         ]
      },
      {
         "id": "2",
         "detectedLanguages": [
            {
               "name": "Spanish",
               "iso6391Name": "es",
               "score": 1.0
            }
         ]
      },
      {
         "id": "3",
         "detectedLanguages": [
            {
               "name": "Chinese_Simplified",
               "iso6391Name": "zh_chs",
               "score": 1.0
            }
         ]
      }
   ],
   "errors": [

   ]
}

分析情绪Analyze sentiment

情绪分析 API 使用 Sentiment 方法检测一组文本记录的情绪。The Sentiment Analysis API detects the sentiment of a set of text records, using the Sentiment method. 以下示例为两个文档打分,一个是英文文档,另一个是西班牙文文档。The following example scores two documents, one in English and another in Spanish.

  1. 在你喜欢使用的代码编辑器中新建一个 Go 项目。Create a new Go project in your favorite code editor.
  2. 添加以下提供的代码。Add the code provided below.
  3. subscriptionKey 值替换为对你的订阅有效的访问密钥。Replace the subscriptionKey value with an access key valid for your subscription.
  4. uriBase 中的位置(当前为 chinaeast2)替换为进行注册的区域。Replace the location in uriBase (currently chinaeast2) to the region you signed up for.
  5. 使用“.go”扩展名保存文件。Save the file with a '.go' extension.
  6. 从根文件夹中安装了 Go 的计算机上打开命令提示符。Open a command prompt on a computer with Go installed from your root folder.
  7. 生成文件,例如:go build sentiment.goBuild the file, for example: go build sentiment.go.
  8. 运行文件,例如:go run sentiment.goRun the file, for example: go run sentiment.go.
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
    "time"
)

func main() {
    // Replace the subscriptionKey string value with your valid subscription key
    const subscriptionKey = "<Subscription Key>"

    /*
    Replace or verify the region.

    You must use the same region in your REST API call as you used to obtain your access keys.
    For example, if you obtained your access keys from the chinanorth region, replace 
    "chinaeast2" in the URI below with "chinanorth".

    */
    const uriBase =    "https://chinaeast2.api.cognitive.azure.cn"
    const uriPath = "/text/analytics/v2.1/sentiment"

    const uri = uriBase + uriPath

    data := []map[string]string{
        {"id": "1", "language": "en", "text": "I really enjoy the new XBox One S. It has a clean look, it has 4K/HDR resolution and it is affordable."},
        {"id": "2", "language": "es", "text": "Este ha sido un dia terrible, llegué tarde al trabajo debido a un accidente automobilistico."},
    }

    documents, err := json.Marshal(&data)
    if err != nil {
        fmt.Printf("Error marshaling data: %v\n", err)
        return
    }

    r := strings.NewReader("{\"documents\": " + string(documents) + "}")

    client := &http.Client{
        Timeout: time.Second * 2,
    }

    req, err := http.NewRequest("POST", uri, r)
    if err != nil {
        fmt.Printf("Error creating request: %v\n", err)
        return
    }

    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)

    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error on request: %v\n", err)
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("Error reading response body: %v\n", err)
        return
    }

    var f interface{}
    json.Unmarshal(body, &f)

    jsonFormatted, err := json.MarshalIndent(f, "", "  ")
    if err != nil {
        fmt.Printf("Error producing JSON: %v\n", err)
        return
    }
    fmt.Println(string(jsonFormatted))
}

分析情绪响应Analyze sentiment response

如果得分接近 1.0,则测量结果为积极;如果得分接近 0.0,则测量结果为消极。The result is measured as positive if it's scored closer to 1.0 and negative if it's scored closer to 0.0. 在 JSON 中返回成功的响应,如以下示例所示:A successful response is returned in JSON, as shown in the following example:

{
   "documents": [
      {
         "score": 0.99984133243560791,
         "id": "1"
      },
      {
         "score": 0.024017512798309326,
         "id": "2"
      },
   ],
   "errors": [   ]
}

提取关键短语Extract key phrases

关键短语提取 API 使用关键短语方法从文本文档中提取关键短语。The Key Phrase Extraction API extracts key-phrases from a text document, using the Key Phrases method. 以下示例为英文和西班牙文文档提取关键短语。The following example extracts key phrases for both English and Spanish documents.

  1. 在你喜欢使用的代码编辑器中新建一个 Go 项目。Create a new Go project in your favorite code editor.
  2. 添加以下提供的代码。Add the code provided below.
  3. subscriptionKey 值替换为对你的订阅有效的访问密钥。Replace the subscriptionKey value with an access key valid for your subscription.
  4. uriBase 中的位置(当前为 chinaeast2)替换为进行注册的区域。Replace the location in uriBase (currently chinaeast2) to the region you signed up for.
  5. 使用“.go”扩展名保存文件。Save the file with a '.go' extension.
  6. 在安装了 Go 的计算机上打开命令提示符。Open a command prompt on a computer with Go installed.
  7. 生成文件,例如:go build key-phrases.goBuild the file, for example: go build key-phrases.go.
  8. 运行文件,例如:go run key-phrases.goRun the file, for example: go run key-phrases.go.
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
    "time"
)

func main() {
    // Replace the subscriptionKey string value with your valid subscription key
    const subscriptionKey = "<Subscription Key>"

    /*
    Replace or verify the region.

    You must use the same region in your REST API call as you used to obtain your access keys.
    For example, if you obtained your access keys from the chinanorth region, replace 
    "chinaeast2" in the URI below with "chinanorth".

    */
    const uriBase =    "https://chinaeast2.api.cognitive.azure.cn"
    const uriPath = "/text/analytics/v2.1/keyPhrases"

    const uri = uriBase + uriPath

    data := []map[string]string{
        {"id": "1", "language": "en", "text": "I really enjoy the new XBox One S. It has a clean look, it has 4K/HDR resolution and it is affordable."},
        {"id": "2", "language": "es", "text": "Si usted quiere comunicarse con Carlos, usted debe de llamarlo a su telefono movil. Carlos es muy responsable, pero necesita recibir una notificacion si hay algun problema."},
        {"id": "3", "language": "en", "text": "The Grand Hotel is a new hotel in the center of Seattle. It earned 5 stars in my review, and has the classiest decor I've ever seen."},
    }

    documents, err := json.Marshal(&data)
    if err != nil {
        fmt.Printf("Error marshaling data: %v\n", err)
        return
    }

    r := strings.NewReader("{\"documents\": " + string(documents) + "}")

    client := &http.Client{
        Timeout: time.Second * 2,
    }

    req, err := http.NewRequest("POST", uri, r)
    if err != nil {
        fmt.Printf("Error creating request: %v\n", err)
        return
    }

    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)

    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error on request: %v\n", err)
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("Error reading response body: %v\n", err)
        return
    }

    var f interface{}
    json.Unmarshal(body, &f)

    jsonFormatted, err := json.MarshalIndent(f, "", "  ")
    if err != nil {
        fmt.Printf("Error producing JSON: %v\n", err)
        return
    }
    fmt.Println(string(jsonFormatted))
}

提取关键短语响应Extract key phrases response

在 JSON 中返回成功的响应,如以下示例所示:A successful response is returned in JSON, as shown in the following example:

{
   "documents": [
      {
         "keyPhrases": [
            "HDR resolution",
            "new XBox",
            "clean look"
         ],
         "id": "1"
      },
      {
         "keyPhrases": [
            "Carlos",
            "notificacion",
            "algun problema",
            "telefono movil"
         ],
         "id": "2"
      },
      {
         "keyPhrases": [
            "new hotel",
            "Grand Hotel",
            "review",
            "center of Seattle",
            "classiest decor",
            "stars"
         ],
         "id": "3"
      }
   ],
   "errors": [  ]
}

识别实体Identify entities

实体 API 使用实体方法识别文本文档中的已知实体。The Entities API identifies well-known entities in a text document, using the Entities method. 实体从文本中提取字词。Entities extract words from text. 以下示例识别英文文档的实体。The following example identifies entities for English documents.

  1. 在你喜欢使用的代码编辑器中新建一个 Go 项目。Create a new Go project in your favorite code editor.
  2. 添加以下提供的代码。Add the code provided below.
  3. subscriptionKey 值替换为对你的订阅有效的访问密钥。Replace the subscriptionKey value with an access key valid for your subscription.
  4. uriBase 中的位置(当前为 chinaeast2)替换为进行注册的区域。Replace the location in uriBase (currently chinaeast2) to the region you signed up for.
  5. 使用“.go”扩展名保存文件。Save the file with a '.go' extension.
  6. 在安装了 Go 的计算机上打开命令提示符。Open a command prompt on a computer with Go installed.
  7. 生成文件,例如:go build entities.goBuild the file, for example: go build entities.go.
  8. 运行文件,例如:go run entities.goRun the file, for example: go run entities.go.
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
    "time"
)

func main() {
    // Replace the subscriptionKey string value with your valid subscription key
    const subscriptionKey = "<Subscription Key>"

    /*
    Replace or verify the region.

    You must use the same region in your REST API call as you used to obtain your access keys.
    For example, if you obtained your access keys from the chinanorth region, replace 
    "chinaeast2" in the URI below with "chinanorth".

    */
    const uriBase =    "https://chinaeast2.api.cognitive.azure.cn"
    const uriPath = "/text/analytics/v2.1/entities"

    const uri = uriBase + uriPath

    data := []map[string]string{
        {"id": "1", "language": "en", "text": "Microsoft is an It company."}
    }

    documents, err := json.Marshal(&data)
    if err != nil {
        fmt.Printf("Error marshaling data: %v\n", err)
        return
    }

    r := strings.NewReader("{\"documents\": " + string(documents) + "}")

    client := &http.Client{
        Timeout: time.Second * 2,
    }

    req, err := http.NewRequest("POST", uri, r)
    if err != nil {
        fmt.Printf("Error creating request: %v\n", err)
        return
    }

    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)

    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error on request: %v\n", err)
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("Error reading response body: %v\n", err)
        return
    }

    var f interface{}
    json.Unmarshal(body, &f)

    jsonFormatted, err := json.MarshalIndent(f, "", "  ")
    if err != nil {
        fmt.Printf("Error producing JSON: %v\n", err)
        return
    }
    fmt.Println(string(jsonFormatted))
}

实体提取响应Entity extraction response

在 JSON 中返回成功的响应,如以下示例所示:A successful response is returned in JSON, as shown in the following example:

{  
   "documents":[  
      {  
         "id":"1",
         "entities":[  
            {  
               "name":"Microsoft",
               "matches":[  
                  {  
                     "wikipediaScore":0.20872054383103444,
                     "entityTypeScore":0.99996185302734375,
                     "text":"Microsoft",
                     "offset":0,
                     "length":9
                  }
               ],
               "wikipediaLanguage":"en",
               "wikipediaId":"Microsoft",
               "wikipediaUrl":"https://en.wikipedia.org/wiki/Microsoft",
               "bingId":"a093e9b9-90f5-a3d5-c4b8-5855e1b01f85",
               "type":"Organization"
            },
            {  
               "name":"Technology company",
               "matches":[  
                  {  
                     "wikipediaScore":0.82123868042800585,
                     "text":"It company",
                     "offset":16,
                     "length":10
                  }
               ],
               "wikipediaLanguage":"en",
               "wikipediaId":"Technology company",
               "wikipediaUrl":"https://en.wikipedia.org/wiki/Technology_company",
               "bingId":"bc30426e-22ae-7a35-f24b-454722a47d8f"
            }
         ]
      }
   ],
    "errors":[]
}

后续步骤Next steps

另请参阅See also

文本分析概述Text Analytics overview
常见问题解答 (FAQ)Frequently asked questions (FAQ)