快速入门:使用“翻译”来翻译文本Quickstart: Use the Translator to translate text

本快速入门介绍如何使用翻译 REST API 将英语文本字符串翻译为德语、意大利语、日语和泰语。In this quickstart, you'll learn how to translate a text string from English to German, Italian, Japanese, and Thai using the Translator REST API.

此快速入门需要包含“翻译”资源的 Azure 认知服务帐户This quickstart requires an Azure Cognitive Services account with a Translator resource.

先决条件Prerequisites

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

设置Set up

创建“翻译”资源Create a Translator resource

Azure 认知服务由你订阅的 Azure 资源表示。Azure Cognitive Services are represented by Azure resources that you subscribe to. 在本地计算机上使用 Azure 门户Azure CLI 创建用于“翻译”的资源。Create a resource for Translator using the Azure portal or Azure CLI on your local machine. 你还可以:You can also:

从试用订阅或资源获取密钥后,创建两个环境变量After you get a key from your trial subscription or resource, create two environment variables:

  • TRANSLATOR_TEXT_SUBSCRIPTION_KEY - “翻译”资源的订阅密钥。TRANSLATOR_TEXT_SUBSCRIPTION_KEY - The subscription key for your Translator resource.
  • TRANSLATOR_TEXT_ENDPOINT - 翻译器的终结点。TRANSLATOR_TEXT_ENDPOINT - The endpoint for Translator. 改用 https://api.translator.azure.cn/Use https://api.translator.azure.cn/.

创建 .NET Core 项目Create a .NET Core project

打开新的命令提示符(或终端会话)并运行以下命令:Open a new command prompt (or terminal session) and run these commands:

dotnet new console -o translate-sample
cd translate-sample

第一个命令执行两项操作。The first command does two things. 它创建新的 .NET 控制台应用程序,并创建名为 translate-sample 的目录。It creates a new .NET console application, and creates a directory named translate-sample. 第二个命令是切换至项目目录。The second command changes to the directory for your project.

接下来需安装 Json.Net。Next, you'll need to install Json.Net. 在项目的目录中,运行以下命令:From your project's directory, run:

dotnet add package Newtonsoft.Json --version 11.0.2

选择 C# 语言版本Select the C# language version

本快速入门需要 C# 7.1 或更高版本。This quickstart requires C# 7.1 or later. 可以通过多种方式来更改项目的 C# 版本。There are a few ways to change the C# version for your project. 本指南将介绍如何调整 translate-sample.csproj 文件。In this guide, we'll show you how to adjust the translate-sample.csproj file. 如需所有可用选项,例如在 Visual Studio 中更改语言的选项,请参阅选择 C# 语言版本For all available options, such as changing the language in Visual Studio, see Select the C# language version.

打开项目,然后打开 translate-sample.csprojOpen your project, then open translate-sample.csproj. 确保将 LangVersion 设置为 7.1 或更高版本。Make sure that LangVersion is set to 7.1 or later. 如果没有用于语言版本的属性组,请添加以下行:If there isn't a property group for the language version, add these lines:

<PropertyGroup>
   <LangVersion>7.1</LangVersion>
</PropertyGroup>

将所需命名空间添加到项目Add required namespaces to your project

此前运行的 dotnet new console 命令创建了一个项目(包括 Program.cs)。The dotnet new console command that you ran earlier created a project, including Program.cs. 此文件是需放置应用程序代码的位置。This file is where you'll put your application code. 打开 Program.cs,替换现有的 using 语句。Open Program.cs, and replace the existing using statements. 这些语句可确保你有权访问生成并运行示例应用所需的所有类型。These statements ensure that you have access to all the types required to build and run the sample app.

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
// Install Newtonsoft.Json with NuGet
using Newtonsoft.Json;

为 JSON 响应创建类Create classes for the JSON response

接下来,我们将创建一组类,在反序列化翻译返回的 JSON 响应时使用。Next, we're going to create a set of classes that are used when deserializing the JSON response returned by the Translator.

/// <summary>
/// The C# classes that represents the JSON returned by the Translator.
/// </summary>
public class TranslationResult
{
    public DetectedLanguage DetectedLanguage { get; set; }
    public TextResult SourceText { get; set; }
    public Translation[] Translations { get; set; }
}

public class DetectedLanguage
{
    public string Language { get; set; }
    public float Score { get; set; }
}

public class TextResult
{
    public string Text { get; set; }
    public string Script { get; set; }
}

public class Translation
{
    public string Text { get; set; }
    public TextResult Transliteration { get; set; }
    public string To { get; set; }
    public Alignment Alignment { get; set; }
    public SentenceLength SentLen { get; set; }
}

public class Alignment
{
    public string Proj { get; set; }
}

public class SentenceLength
{
    public int[] SrcSentLen { get; set; }
    public int[] TransSentLen { get; set; }
}

从环境变量获取订阅信息Get subscription information from environment variables

将以下行添加到 Program 类。Add the following lines to the Program class. 这些行将从环境变量中读取订阅密钥和终结点,并在遇到任何问题时引发错误。These lines read your subscription key and endpoint from environment variables, and throws an error if you run into any issues.

private const string key_var = "TRANSLATOR_TEXT_SUBSCRIPTION_KEY";
private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var);

private const string endpoint_var = "TRANSLATOR_TEXT_ENDPOINT";
private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var);

static Program()
{
    if (null == subscriptionKey)
    {
        throw new Exception("Please set/export the environment variable: " + key_var);
    }
    if (null == endpoint)
    {
        throw new Exception("Please set/export the environment variable: " + endpoint_var);
    }
}
// The code in the next section goes here.

创建文本翻译函数Create a function to translate text

Program 类中,创建一个名为 TranslateTextRequest() 的异步函数。In the Program class, create an asynchronous function called TranslateTextRequest(). 此函数采用四个参数:subscriptionKeyhostrouteinputTextThis function takes four arguments: subscriptionKey, host, route, and inputText.

// This sample requires C# 7.1 or later for async/await.
// Async call to the Translator
static public async Task TranslateTextRequest(string subscriptionKey, string endpoint, string route, string inputText)
{
  /*
   * The code for your call to the translation service will be added to this
   * function in the next few sections.
   */
}

序列化翻译请求Serialize the translation request

接下来需创建 JSON 对象并将其序列化,其中包含要翻译的文本。Next, we need to create and serialize the JSON object that includes the text you want to translate. 请记住,可以在 body 中传递多个对象。Keep in mind, you can pass more than one object in the body.

object[] body = new object[] { new { Text = inputText } };
var requestBody = JsonConvert.SerializeObject(body);

实例化客户端并发出请求Instantiate the client and make a request

以下行实例化 HttpClientHttpRequestMessageThese lines instantiate the HttpClient and the HttpRequestMessage:

using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
  // In the next few sections you'll add code to construct the request.
}

构造请求并输出响应Construct the request and print the response

HttpRequestMessage 中,需执行以下操作:Inside the HttpRequestMessage you'll:

  • 声明 HTTP 方法Declare the HTTP method
  • 构造请求 URIConstruct the request URI
  • 插入请求正文(序列化的 JSON 对象)Insert the request body (serialized JSON object)
  • 添加必需的标头Add required headers
  • 发出异步请求Make an asynchronous request
  • 使用之前创建的类输出响应Print the response using the classes you created earlier

HttpRequestMessage 添加以下代码:Add this code to the HttpRequestMessage:

// Build the request.
// Set the method to Post.
request.Method = HttpMethod.Post;
// Construct the URI and add headers.
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

// Send the request and get response.
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
// Read response as a string.
string result = await response.Content.ReadAsStringAsync();
// Deserialize the response using the classes created earlier.
TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
// Iterate over the deserialized results.
foreach (TranslationResult o in deserializedOutput)
{
    // Print the detected input language and confidence score.
    Console.WriteLine("Detected input language: {0}\nConfidence score: {1}\n", o.DetectedLanguage.Language, o.DetectedLanguage.Score);
    // Iterate over the results and print each translation.
    foreach (Translation t in o.Translations)
    {
        Console.WriteLine("Translated to {0}: {1}", t.To, t.Text);
    }
}

如果使用的是认知服务多服务订阅,则还必须在请求参数中包括 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.

将其放在一起Put it all together

最后一步是在 Main 函数中调用 TranslateTextRequest()The last step is to call TranslateTextRequest() in the Main function. 在此示例中,我们将翻译为德语 (de)、意大利语 (it)、日语 (ja) 和泰语 (th)。In this sample, we're translating to German (de), Italian (it), Japanese (ja), and Thai (th). 找到 static void Main(string[] args) 并将其替换为以下代码:Locate static void Main(string[] args) and replace it with this code:

static async Task Main(string[] args)
{
    // This is our main function.
    // Output languages are defined in the route.
    // For a complete list of options, see API reference.
    // /cognitive-services/translator/reference/v3-0-translate
    string route = "/translate?api-version=3.0&to=de&to=it&to=ja&to=th";
    // Prompts you for text to translate. If you'd prefer, you can
    // provide a string as textToTranslate.
    Console.Write("Type the phrase you'd like to translate? ");
    string textToTranslate = Console.ReadLine();
    await TranslateTextRequest(subscriptionKey, endpoint, route, textToTranslate);
    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

你会注意到,在 Main 中声明了 subscriptionKeyendpointrouteYou'll notice that in Main, you're declaring subscriptionKey, endpoint, and route. 此外,你将使用 Console.Readline() 提示用户输入并将值分配给 textToTranslateAdditionally, you're prompting the user for input with Console.Readline() and assigning the value to textToTranslate.

运行示例应用Run the sample app

上述操作完成后,就可以运行示例应用了。That's it, you're ready to run your sample app. 从命令行(或终端会话)导航到项目目录,然后运行以下命令:From the command line (or terminal session), navigate to your project directory and run:

dotnet run

示例响应Sample response

运行示例后,应当会看到输出到终端的以下内容:After you run the sample, you should see the following printed to terminal:

Detected input language: en
Confidence score: 1

Translated to de: Hallo Welt!
Translated to it: Salve, mondo!
Translated to ja: ハローワールド!
Translated to th: หวัดดีชาวโลก!

此消息是从原始 JSON 构建的,如下所示:This message is built from the raw JSON, which will look like this:

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "translations": [
      {
        "text": "Hallo Welt!",
        "to": "de"
      },
      {
        "text": "Salve, mondo!",
        "to": "it"
      },
      {
        "text": "ハローワールド!",
        "to": "ja"
      },
      {
        "text": "หวัดดีชาวโลก!",
        "to": "th"
      }
    ]
  }
]

清理资源Clean up resources

请务必删除示例应用的源代码中的机密信息,例如订阅密钥。Make sure to remove any confidential information from your sample app's source code, like subscription keys.

后续步骤Next steps

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

先决条件Prerequisites

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

设置Set up

创建“翻译”资源Create a Translator resource

Azure 认知服务由你订阅的 Azure 资源表示。Azure Cognitive Services are represented by Azure resources that you subscribe to. 在本地计算机上使用 Azure 门户Azure CLI 创建用于“翻译”的资源。Create a resource for Translator using the Azure portal or Azure CLI on your local machine. 你还可以:You can also:

从试用订阅或资源获取密钥后,创建两个环境变量After you get a key from your trial subscription or resource, create two environment variables:

  • TRANSLATOR_TEXT_SUBSCRIPTION_KEY - “翻译”资源的订阅密钥。TRANSLATOR_TEXT_SUBSCRIPTION_KEY - The subscription key for your Translator resource.
  • TRANSLATOR_TEXT_ENDPOINT - 翻译器的终结点。TRANSLATOR_TEXT_ENDPOINT - The endpoint for Translator. 改用 https://api.translator.azure.cn/Use https://api.translator.azure.cn/.

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

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

package main

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

创建 main 函数Create the main function

此示例将尝试从以下环境变量中读取“翻译”订阅密钥和终结点:TRANSLATOR_TEXT_SUBSCRIPTION_KEYTRANSLATOR_TEXT_ENDPOINTThis sample will try to read your Translator subscription key and endpoint from these environment variables: TRANSLATOR_TEXT_SUBSCRIPTION_KEY and TRANSLATOR_TEXT_ENDPOINT. 如果不熟悉环境变量,则可将 subscriptionKeyendpoint 设置为字符串并注释掉条件语句。If you're not familiar with environment variables, you can set subscriptionKey and endpoint as strings and comment out the conditional statements.

将以下代码复制到项目中: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.
    */
    if "" == os.Getenv("TRANSLATOR_TEXT_SUBSCRIPTION_KEY") {
      log.Fatal("Please set/export the environment variable TRANSLATOR_TEXT_SUBSCRIPTION_KEY.")
    }
    subscriptionKey := os.Getenv("TRANSLATOR_TEXT_SUBSCRIPTION_KEY")
    if "" == os.Getenv("TRANSLATOR_TEXT_ENDPOINT") {
      log.Fatal("Please set/export the environment variable TRANSLATOR_TEXT_ENDPOINT.")
    }
    endpoint := os.Getenv("TRANSLATOR_TEXT_ENDPOINT")
    uri := endpoint + "/translate?api-version=3.0"
    /*
     * This calls our breakSentence function, which we'll
     * create in the next section. It takes a single argument,
     * the subscription key.
     */
    translate(subscriptionKey, uri)
}

创建文本翻译函数Create a function to translate text

让我们创建文本翻译函数。Let's create a function to translate text. 此函数将接受一个参数,即“翻译”订阅密钥。This function will take a single argument, your Translator subscription key.

func translate(subscriptionKey string, uri 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. 在此示例中,将从英语翻译为德语和意大利语:deitIn this sample, you're translating from English to German and Italian: de and it.

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

// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("to", "de")
q.Add("to", "it")
u.RawQuery = q.Encode()

备注

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

创建请求正文的结构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(). 将此代码添加到 translate 函数中。Add this code to the translate function.

// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
    Text string
}{
    {Text: "Hello, world!"},
}
b, _ := json.Marshal(body)

生成请求Build the request

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

// 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("Content-Type", "application/json")

// Call the Translator
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

将此代码添加到 translate 函数以解码 JSON 响应,然后格式化并输出结果。Add this code to the translate 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

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

go run translate-text.go

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

示例响应Sample response

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

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "translations": [
      {
        "text": "Hallo Welt!",
        "to": "de"
      },
      {
        "text": "Salve, mondo!",
        "to": "it"
      }
    ]
  }
]

后续步骤Next steps

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

先决条件Prerequisites

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

设置Set up

创建“翻译”资源Create a Translator resource

Azure 认知服务由你订阅的 Azure 资源表示。Azure Cognitive Services are represented by Azure resources that you subscribe to. 在本地计算机上使用 Azure 门户Azure CLI 创建用于“翻译”的资源。Create a resource for Translator using the Azure portal or Azure CLI on your local machine. 你还可以:You can also:

从试用订阅或资源获取密钥后,创建两个环境变量After you get a key from your trial subscription or resource, create two environment variables:

  • TRANSLATOR_TEXT_SUBSCRIPTION_KEY - “翻译”资源的订阅密钥。TRANSLATOR_TEXT_SUBSCRIPTION_KEY - The subscription key for your Translator resource.
  • TRANSLATOR_TEXT_ENDPOINT - 翻译器的终结点。TRANSLATOR_TEXT_ENDPOINT - The endpoint for Translator. 改用 https://api.translator.azure.cn/Use https://api.translator.azure.cn/.

使用 Gradle 初始化项目Initialize a project with Gradle

首先,创建此项目的工作目录。Let's start by creating a working directory for this project. 从命令行(或终端)中,运行以下命令:From the command line (or terminal), run this command:

mkdir translator-sample
cd translator-sample

接下来,初始化一个 Gradle 项目。Next, you're going to initialize a Gradle project. 此命令将创建 Gradle 的基本生成文件,最重要的是 build.gradle.kts,它在运行时用来创建并配置应用程序。This command will create essential build files for Gradle, most importantly, the build.gradle.kts, which is used at runtime to create and configure your application. 从工作目录运行以下命令:Run this command from your working directory:

gradle init --type basic

当提示你选择一个 DSL 时,选择 KotlinWhen prompted to choose a DSL , select Kotlin .

配置生成文件Configure the build file

找到 build.gradle.kts 并使用你喜欢使用的 IDE 或文本编辑器将其打开。Locate build.gradle.kts and open it with your favorite IDE or text editor. 然后将以下生成配置复制到其中:Then copy in this build configuration:

plugins {
    java
    application
}
application {
    mainClassName = "Translate"
}
repositories {
    mavenCentral()
}
dependencies {
    compile("com.squareup.okhttp:okhttp:2.5.0")
    compile("com.google.code.gson:gson:2.8.5")
}

请注意,此示例依赖于 HTTP 请求的 OkHttp 以及 Gson 来处理和分析 JSON。Take note that this sample has dependencies on OkHttp for HTTP requests, and Gson to handle and parse JSON. 如果要详细了解生成配置,请参阅创建新的 Gradle 生成If you'd like to learn more about build configurations, see Creating New Gradle Builds.

创建 Java 文件Create a Java file

为示例应用创建一个文件夹。Let's create a folder for your sample app. 从工作目录中,运行:From your working directory, run:

mkdir -p src/main/java

接下来,在此文件夹中,创建一个名为 Translate.java 的文件。Next, in this folder, create a file named Translate.java.

导入所需的库Import required libraries

打开 Translate.java 并添加以下 import 语句:Open Translate.java and add these import statements:

import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;

定义变量Define variables

首先,为你的项目创建一个公共类:First, you'll need to create a public class for your project:

public class Translate {
  // All project code goes here...
}

将以下行添加到 Translate 类。Add these lines to the Translate class. 首先,从环境变量中读取订阅密钥和终结点。First, the subscription key and endpoint are being read from environment variables. 然后,你会注意到,除了 api-version 之外,还向 url 追加了两个参数。Then, you'll notice that along with the api-version, two additional parameters have been appended to the url. 这些参数用于设置翻译输出。These parameters are used to set the translation outputs. 在此示例中,它设置为德语 (de) 和意大利语 (it)。In this sample, it's set to German (de) and Italian (it).

private static String subscriptionKey = System.getenv("TRANSLATOR_TEXT_SUBSCRIPTION_KEY");
private static String endpoint = System.getenv("TRANSLATOR_TEXT_ENDPOINT");
String url = endpoint + "/translate?api-version=3.0&to=de,it";

如果使用的是认知服务多服务订阅,则还必须在请求参数中包括 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.

创建客户端并生成请求Create a client and build a request

将以下行添加到 Translate 类来实例化 OkHttpClientAdd this line to the Translate class to instantiate the OkHttpClient:

// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();

接下来,我们将生成 POST 请求。Next, let's build the POST request. 可随意更改用于翻译的文本。Feel free to change the text for translation. 文本必须进行转义。The text must be escaped.

// This function performs a POST request.
public String Post() throws IOException {
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType,
            "[{\n\t\"Text\": \"Welcome to Microsoft Translator. Guess how many languages I speak!\"\n}]");
    Request request = new Request.Builder()
            .url(url).post(body)
            .addHeader("Ocp-Apim-Subscription-Key", subscriptionKey)
            .addHeader("Content-type", "application/json").build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}

创建一个函数来分析响应Create a function to parse the response

这个简单的函数分析来自“翻译”服务的 JSON 响应并对其进行美化。This simple function parses and prettifies the JSON response from the Translator service.

// This function prettifies the json response.
public static String prettify(String json_text) {
    JsonParser parser = new JsonParser();
    JsonElement json = parser.parse(json_text);
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    return gson.toJson(json);
}

将其放在一起Put it all together

最后一步是发出请求并获得响应。The last step is to make a request and get a response. 将以下行添加你的项目:Add these lines to your project:

public static void main(String[] args) {
    try {
        Translate translateRequest = new Translate();
        String response = translateRequest.Post();
        System.out.println(prettify(response));
    } catch (Exception e) {
        System.out.println(e);
    }
}

运行示例应用Run the sample app

上述操作完成后,就可以运行示例应用了。That's it, you're ready to run your sample app. 从命令行(或终端会话)导航到工作目录的根,然后运行以下命令:From the command line (or terminal session), navigate to the root of your working directory and run:

gradle build

当生成完成后,请运行:When the build completes, run:

gradle run

示例响应Sample response

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "translations": [
      {
        "text": "Willkommen bei Microsoft Translator. Erraten Sie, wie viele Sprachen ich spreche!",
        "to": "de"
      },
      {
        "text": "Benvenuti a Microsoft Translator. Indovinate quante lingue parlo!",
        "to": "it"
      }
    ]
  }
]

后续步骤Next steps

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

先决条件Prerequisites

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

设置Set up

创建“翻译”资源Create a Translator resource

Azure 认知服务由你订阅的 Azure 资源表示。Azure Cognitive Services are represented by Azure resources that you subscribe to. 在本地计算机上使用 Azure 门户Azure CLI 创建用于“翻译”的资源。Create a resource for Translator using the Azure portal or Azure CLI on your local machine. 你还可以:You can also:

从试用订阅或资源获取密钥后,创建两个环境变量After you get a key from your trial subscription or resource, create two environment variables:

  • TRANSLATOR_TEXT_SUBSCRIPTION_KEY - “翻译”资源的订阅密钥。TRANSLATOR_TEXT_SUBSCRIPTION_KEY - The subscription key for your Translator resource.
  • TRANSLATOR_TEXT_ENDPOINT - 翻译器的终结点。TRANSLATOR_TEXT_ENDPOINT - The endpoint for Translator. 改用 https://api.translator.azure.cn/Use https://api.translator.azure.cn/.

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

使用你喜欢的 IDE 或编辑器创建一个新项目,或者在桌面上创建一个包含名为 translate-text.js 的文件的新文件夹。Create a new project using your favorite IDE or editor, or a new folder with a file named translate-text.js on your desktop. 然后将以下代码片段复制到项目/文件中:Then copy this code snippet into your project/file:

const request = require('request');
const uuidv4 = require('uuid/v4');

备注

如果尚未使用这些模块,则需在运行程序之前安装它们。If you haven't used these modules you'll need to install them before running your program. 若要安装这些包,请运行 npm install request uuidv4To install these packages, run: npm install request uuidv4.

若要构造 HTTP 请求以及为 'X-ClientTraceId' 标头创建唯一标识符,必须使用这些模块。These modules are required to construct the HTTP request, and create a unique identifier for the 'X-ClientTraceId' header.

设置订阅密钥和终结点Set the subscription key and endpoint

此示例将尝试从以下环境变量中读取“翻译”订阅密钥和终结点:TRANSLATOR_TEXT_SUBSCRIPTION_KEYTRANSLATOR_TEXT_ENDPOINTThis sample will try to read your Translator subscription key and endpoint from these environment variables: TRANSLATOR_TEXT_SUBSCRIPTION_KEY and TRANSLATOR_TEXT_ENDPOINT. 如果不熟悉环境变量,则可将 subscriptionKeyendpoint 设置为字符串并注释掉条件语句。If you're not familiar with environment variables, you can set subscriptionKey and endpoint as strings and comment out the conditional statements.

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

var key_var = 'TRANSLATOR_TEXT_SUBSCRIPTION_KEY';
if (!process.env[key_var]) {
    throw new Error('Please set/export the following environment variable: ' + key_var);
}
var subscriptionKey = process.env[key_var];
var endpoint_var = 'TRANSLATOR_TEXT_ENDPOINT';
if (!process.env[endpoint_var]) {
    throw new Error('Please set/export the following environment variable: ' + endpoint_var);
}
var endpoint = process.env[endpoint_var];

配置请求Configure the request

使用通过请求模块提供的 request() 方法,可以以 options 对象的形式传递 HTTP 方法、URL、请求参数、标头和 JSON 正文。The request() method, made available through the request module, allows us to pass the HTTP method, URL, request params, headers, and the JSON body as an options object. 在此代码片段中,我们将配置请求:In this code snippet, we'll configure the request:

备注

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

let options = {
    method: 'POST',
    baseUrl: endpoint,
    url: 'translate',
    qs: {
      'api-version': '3.0',
      'to': ['de', 'it']
    },
    headers: {
      'Ocp-Apim-Subscription-Key': subscriptionKey,
      'Content-type': 'application/json',
      'X-ClientTraceId': uuidv4().toString()
    },
    body: [{
          'text': 'Hello World!'
    }],
    json: true,
};

若要对请求进行身份验证,最容易的方法是将订阅密钥作为 Ocp-Apim-Subscription-Key 标头传入,这是我们在此示例中使用的方法。The easiest way to authenticate a request is to pass in your subscription key as an Ocp-Apim-Subscription-Key header, which is what we use in this sample. 替代方法是交换订阅密钥来获取访问令牌,将访问令牌作为 Authorization 标头传入,以便对请求进行验证。As an alternative, you can exchange your subscription key for an access token, and pass the access token along as an Authorization header to validate your request.

如果使用的是认知服务多服务订阅,则还必须在请求标头中包括 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 headers.

有关详细信息,请参阅身份验证For more information, see Authentication.

发出请求并输出响应Make the request and print the response

接下来,请使用 request() 方法来创建请求。Next, we'll create the request using the request() method. 它采用我们在上一部分创建的 options 对象作为第一个参数,然后输出美化的 JSON 响应。It takes the options object that we created in the previous section as the first argument, then prints the prettified JSON response.

request(options, function(err, res, body){
    console.log(JSON.stringify(body, null, 4));
});

备注

在此示例中,我们将在 options 对象中定义 HTTP 请求。In this sample, we're defining the HTTP request in the options object. 不过,请求模块也支持便捷方法,例如 .post.getHowever, the request module also supports convenience methods, like .post and .get. 有关详细信息,请参阅便捷方法For more information, see convenience methods.

将其放在一起Put it all together

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

node translate-text.js

如果希望将你的代码与我们的进行比较,请查看 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
        },
        "translations": [
            {
                "text": "Hallo Welt!",
                "to": "de"
            },
            {
                "text": "Salve, mondo!",
                "to": "it"
            }
        ]
    }
]

清理资源Clean up resources

如果已将订阅密钥硬编码到程序中,请确保在完成本快速入门后删除该订阅密钥。If you've hardcoded your subscription key into your program, make sure to remove the subscription key when you're finished with this quickstart.

后续步骤Next steps

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

先决条件Prerequisites

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

设置Set up

创建“翻译”资源Create a Translator resource

Azure 认知服务由你订阅的 Azure 资源表示。Azure Cognitive Services are represented by Azure resources that you subscribe to. 在本地计算机上使用 Azure 门户Azure CLI 创建用于“翻译”的资源。Create a resource for Translator using the Azure portal or Azure CLI on your local machine. 你还可以:You can also:

从试用订阅或资源获取密钥后,创建两个环境变量After you get a key from your trial subscription or resource, create two environment variables:

  • TRANSLATOR_TEXT_SUBSCRIPTION_KEY - “翻译”资源的订阅密钥。TRANSLATOR_TEXT_SUBSCRIPTION_KEY - The subscription key for your Translator resource.
  • TRANSLATOR_TEXT_ENDPOINT - 翻译器的终结点。TRANSLATOR_TEXT_ENDPOINT - The endpoint for Translator. 改用 https://api.translator.azure.cn/Use https://api.translator.azure.cn/.

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

使用最喜欢的 IDE 或编辑器创建新的 Python 项目。Create a new Python project using your favorite IDE or editor. 然后,将此代码片段复制到项目的名为 translate-text.py 的文件中。Then copy this code snippet into your project in a file named translate-text.py. 请确保 IDE 解释器引用了正确的 Python 版本,以避免无法识别库。Be sure your IDE's interpreter references the correct version of Python to avoid libraries not being recognized.

# -*- coding: utf-8 -*-
import os, requests, uuid, json

备注

如果尚未使用这些模块,则需在运行程序之前安装它们。If you haven't used these modules you'll need to install them before running your program. 若要安装这些包,请运行 pip install requests uuidTo install these packages, run: pip install requests uuid.

第一个注释告知 Python 解释器使用 UTF-8 编码。The first comment tells your Python interpreter to use UTF-8 encoding. 然后导入必需的模块,以便从环境变量读取订阅密钥、构造 HTTP 请求、创建唯一标识符,以及处理“翻译”返回的 JSON 响应。Then required modules are imported to read your subscription key from an environment variable, construct the http request, create a unique identifier, and handle the JSON response returned by the Translator.

设置订阅密钥、终结点和路径Set the subscription key, endpoint, and path

此示例将尝试从以下环境变量中读取“翻译”订阅密钥和终结点:TRANSLATOR_TEXT_KEYTRANSLATOR_TEXT_ENDPOINTThis sample will try to read your Translator subscription key and endpoint from the environment variables: TRANSLATOR_TEXT_KEY and TRANSLATOR_TEXT_ENDPOINT. 如果不熟悉环境变量,则可将 subscription_keyendpoint 设置为字符串并注释掉条件语句。If you're not familiar with environment variables, you can set subscription_key and endpoint as a strings and comment out the conditional statements.

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

key_var_name = 'TRANSLATOR_TEXT_SUBSCRIPTION_KEY'
if not key_var_name in os.environ:
    raise Exception('Please set/export the environment variable: {}'.format(key_var_name))
subscription_key = os.environ[key_var_name]

endpoint_var_name = 'TRANSLATOR_TEXT_ENDPOINT'
if not endpoint_var_name in os.environ:
    raise Exception('Please set/export the environment variable: {}'.format(endpoint_var_name))
endpoint = os.environ[endpoint_var_name]

“翻译”全局终结点设置为 endpointThe Translator global endpoint is set as the endpoint. path 设置 translate 路由并确定我们需使用 API 的版本 3。path sets the translate route and identifies that we want to hit version 3 of the API.

params 用于设置输出语言。The params are used to set the output languages. 在此示例中,我们将从英文翻译为意大利文和德文:itdeIn this sample we're translating from English to Italian and German: it and de.

备注

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

path = '/translate?api-version=3.0'
params = '&to=de&to=it'
constructed_url = endpoint + path + params

添加标头Add headers

若要对请求进行身份验证,最容易的方法是将订阅密钥作为 Ocp-Apim-Subscription-Key 标头传入,这是我们在此示例中使用的方法。The easiest way to authenticate a request is to pass in your subscription key as an Ocp-Apim-Subscription-Key header, which is what we use in this sample. 替代方法是交换订阅密钥来获取访问令牌,将访问令牌作为 Authorization 标头传入,以便对请求进行验证。As an alternative, you can exchange your subscription key for an access token, and pass the access token along as an Authorization header to validate your request. 有关详细信息,请参阅身份验证For more information, see Authentication.

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

headers = {
    'Ocp-Apim-Subscription-Key': subscription_key,
    'Content-type': 'application/json',
    'X-ClientTraceId': str(uuid.uuid4())
}

如果使用的是认知服务多服务订阅,则还必须在请求参数中包括 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.

创建文本翻译请求Create a request to translate text

定义要翻译的字符串:Define the string (or strings) that you want to translate:

body = [{
    'text': 'Hello World!'
}]

接下来,请使用 requests 模块创建一个 POST 请求。Next, we'll create a POST request using the requests module. 它使用三个参数:串联的 URL、请求标头和请求正文:It takes three arguments: the concatenated URL, the request headers, and the request body:

request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()

最后一步是输出结果。The last step is to print the results. 以下代码片段通过将密钥排序、设置缩进以及声明项和密钥分隔符来美化结果。This code snippet prettifies the results by sorting the keys, setting indentation, and declaring item and key separators.

print(json.dumps(response, sort_keys=True, indent=4,
                 ensure_ascii=False, separators=(',', ': ')))

将其放在一起Put it all together

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

python translate-text.py

如果希望将你的代码与我们的进行比较,请查看 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
        },
        "translations": [
            {
                "text": "Hallo Welt!",
                "to": "de"
            },
            {
                "text": "Salve, mondo!",
                "to": "it"
            }
        ]
    }
]

清理资源Clean up resources

如果已将订阅密钥硬编码到程序中,请确保在完成本快速入门后删除该订阅密钥。If you've hardcoded your subscription key into your program, make sure to remove the subscription key when you're finished with this quickstart.

后续步骤Next steps

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

另请参阅See also