快速入门:使用 Go 通过文本翻译 API 来确定句子长度Quickstart: Use the Translator Text API to determine sentence length using Go

本快速入门介绍如何使用 Go 和文本翻译 REST API 来确定句子长度(以字符数为单位)。In this quickstart, you'll learn how to determine sentence lengths (in characters) using Go and the Translator Text REST API.

此快速入门需要包含文本翻译资源的 Azure 认知服务帐户This quickstart requires an Azure Cognitive Services account with a Translator Text resource. 如果没有帐户,可以使用试用帐户获取订阅密钥。If you don't have an account, you can use the trial to get a subscription key.

Tip

如果你想一次看到所有代码,这个示例的源代码可以在 GitHub 上找到。If you'd like to see all the code at once, the source code for this sample is available on GitHub.

先决条件Prerequisites

本快速入门需要:This quickstart requires:

  • GoGo
  • 适用于文本翻译的 Azure 订阅密钥An Azure subscription key for Translator Text

创建一个项目并导入必需的模块Create a project and import required modules

使用最喜欢的 IDE 或编辑器创建新的 Go 项目。Create a new Go project using your favorite IDE or editor. 然后,将此代码片段复制到项目的名为 sentence-length.go 的文件中。Then copy this code snippet into your project in a file named sentence-length.go.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "net/url"
    "os"
)

创建 main 函数Create the main function

此示例将尝试从环境变量 TRANSLATOR_TEXT_KEY 读取文本翻译订阅密钥。This sample will try to read your Translator Text subscription key from the environment variable TRANSLATOR_TEXT_KEY. 如果不熟悉环境变量,则可将 subscriptionKey 设置为字符串并注释掉条件语句。If you're not familiar with environment variables, you can set subscriptionKey as a string and comment out the conditional statement.

将以下代码复制到项目中:Copy this code into your project:

func main() {
    /*
     * Read your subscription key from an env variable.
     * Please note: You can replace this code block with
     * var subscriptionKey = "YOUR_SUBSCRIPTION_KEY" if you don't
     * want to use env variables. If so, be sure to delete the "os" import.
     */
    subscriptionKey := os.Getenv("TRANSLATOR_TEXT_KEY")
    if subscriptionKey == "" {
       log.Fatal("Environment variable TRANSLATOR_TEXT_KEY is not set.")
    }
    /*
     * This calls our breakSentence function, which we'll
     * create in the next section. It takes a single argument,
     * the subscription key.
     */
    breakSentence(subscriptionKey)
}

创建一个用于确定句子长度的函数Create a function to determine sentence length

创建一个用于确定句子长度的函数。Let's create a function to determine sentence length. 此函数将接受一个参数,即文本翻译订阅密钥。This function will take a single argument, your Translator Text subscription key.

func breakSentence(subscriptionKey string) {
    /*  
     * In the next few sections, we'll add code to this
     * function to make a request and handle the response.
     */
}

接下来,构造 URL。Next, let's construct the URL. 使用 Parse()Query() 方法生成 URL。The URL is built using the Parse() and Query() methods. 你将注意到参数是通过 Add() 方法添加的。You'll notice that parameters are added with the Add() method.

将此代码复制到 breakSentence 函数中。Copy this code into the breakSentence function.

// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse("https://api.translator.azure.cn/breaksentence?api-version=3.0")
q := u.Query()
q.Add("languages", "en")
u.RawQuery = q.Encode()

Note

有关终结点、路由和请求参数的详细信息,请参阅文本翻译 API 3.0:断句For more information about endpoints, routes, and request parameters, see Translator Text API 3.0: BreakSentence.

创建请求正文的结构Create a struct for your request body

接下来,创建请求正文的匿名结构,并使用 json.Marshal() 将其编码为 JSON。Next, create an anonymous structure for the request body and encode it as JSON with json.Marshal(). 将此代码添加到 breakSentence 函数中。Add this code to the breakSentence function.

// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
    Text string
}{
    {Text: "How are you? I am fine. What did you do today?"},
}
b, _ := json.Marshal(body)

生成请求Build the request

将请求正文编码为 JSON 后,可以生成 POST 请求并调用文本翻译 API。Now that you've encoded the request body as JSON, you can build your POST request, and call the Translator Text API.

// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
    log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Ocp-Apim-Subscription-Region", "your region")
req.Header.Add("Content-Type", "application/json")

// Call the Translator Text API
res, err := http.DefaultClient.Do(req)
if err != nil {
    log.Fatal(err)
}

如果使用的是认知服务多服务订阅,则还必须在请求参数中包括 Ocp-Apim-Subscription-RegionIf you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. 详细了解如何使用多服务订阅进行身份验证Learn more about authenticating with the multi-service subscription.

处理并输出响应Handle and print the response

将此代码添加到 breakSentence 函数以解码 JSON 响应,然后格式化并输出结果。Add this code to the breakSentence function to decode the JSON response, and then format and print the result.

// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
    log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", "  ")
fmt.Printf("%s\n", prettyJSON)

将其放在一起Put it all together

就是这样,你已构建了一个简单的程序。该程序可以调用文本翻译 API 并返回 JSON 响应。That's it, you've put together a simple program that will call the Translator Text API and return a JSON response. 现在,可以运行该程序了:Now it's time to run your program:

go run sentence-length.go

如果希望将你的代码与我们的进行比较,请查看 GitHub 上提供的完整示例。If you'd like to compare your code against ours, the complete sample is available on GitHub.

示例响应Sample response

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "sentLen": [
      13,
      11,
      22
    ]
  }
]

后续步骤Next steps

查看 API 参考,了解使用文本翻译 API 可以执行的所有操作。Take a look at the API reference to understand everything you can do with the Translator Text API.

另请参阅See also

了解如何使用文本翻译 API 执行以下操作:Learn how to use the Translator Text API to: