快速入门:通过“翻译”对文本进行直译Quickstart: Use the Translator to transliterate text

在本快速入门中,你将了解如何使用翻译 REST API 将文本从一个脚本直译(转换)为另一个脚本。In this quickstart, you'll learn how to transliterate (convert) text from one script to another using the Translator REST API. 在提供的示例中,日语在经过直译后使用拉丁字母。In the sample provided, Japanese is transliterated to use the Latin alphabet.

此快速入门需要包含“翻译”资源的 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 transliterate-sample
cd transliterate-sample

第一个命令执行两项操作。The first command does two things. 它创建新的 .NET 控制台应用程序,并创建名为 transliterate-sample 的目录。It creates a new .NET console application, and creates a directory named transliterate-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. 本指南将介绍如何调整 transliterate-sample.csproj 文件。In this guide, we'll show you how to adjust the transliterate-sample.csproj file. 如需所有可用选项,例如在 Visual Studio 中更改语言的选项,请参阅选择 C# 语言版本For all available options, such as changing the language in Visual Studio, see Select the C# language version.

打开项目,然后打开 transliterate-sample.csprojOpen your project, then open transliterate-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 class that's 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 TransliterationResult
{
    public string Text { get; set; }
    public string Script { 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 transliterate text

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

static public async Task TransliterateTextRequest(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

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.
TransliterationResult[] deserializedOutput = JsonConvert.DeserializeObject<TransliterationResult[]>(result);
// Iterate over the deserialized results.
foreach (TransliterationResult o in deserializedOutput)
{
    Console.WriteLine("Transliterated to {0} script: {1}", o.Script, o.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 函数中调用 TransliterateTextRequest()The last step is to call TransliterateTextRequest() in the Main function. 在此示例中,我们从日语直译为拉丁语脚本。In this sample, we're transliterating from Japanese to latin script. 找到 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-transliterate
    string route = "/transliterate?api-version=3.0&language=ja&fromScript=jpan&toScript=latn";
    string textToTransliterate = @"こんにちは";
    await TransliterateTextRequest(subscriptionKey, endpoint, route, textToTransliterate);
    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

你会注意到,在 Main 中声明了 subscriptionKeyendpointroute 以及要翻译的脚本 textToTransliterateYou'll notice that in Main, you're declaring subscriptionKey, endpoint, route, and the script to transliterate textToTransliterate.

运行示例应用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:

Transliterated to latn script: Kon\'nichiwa

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

[
    {
        "script": "latn",
        "text": "konnichiwa"
    }
]

清理资源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. 然后,将此代码片段复制到项目的名为 transliterate-text.go 的文件中。Then copy this code snippet into your project in a file named transliterate-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 + "/transliterate?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.
     */
    transliterate(subscriptionKey, uri)
}

创建文本直译函数Create a function to transliterate text

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

func transliterate(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. 在此示例中,我们从日语直译为拉丁字母。In this sample, we're transliterating from Japanese to the Latin alphabet.

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

// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("language", "ja")
q.Add("fromScript", "jpan")
q.Add("toScript", "latn")
u.RawQuery = q.Encode()

备注

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

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

// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
  Text string
}{
  {Text: "こんにちは"},
}
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

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

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

示例响应Sample response

[
  {
    "script": "latn",
    "text": "konnichiwa"
  }
]

后续步骤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 transliterate-sample
cd transliterate-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 = "Transliterate"
}
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

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

导入所需的库Import required libraries

打开 Transliterate.java 并添加以下 import 语句:Open Transliterate.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 Transliterate {
  // All project code goes here...
}

将以下行添加到 Transliterate 类。Add these lines to the Transliterate 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 input language, and the scripts for transliteration. 在此示例中,它设置为日语 (jpan) 和拉丁文 (latn)。In this sample, it's set to Japanese (jpan) and Latin (latn).

private static String subscriptionKey = System.getenv("TRANSLATOR_TEXT_SUBSCRIPTION_KEY");
private static String endpoint = System.getenv("TRANSLATOR_TEXT_ENDPOINT");
String url = endpoint + "/transliterate?api-version=3.0&language=ja&fromScript=jpan&toScript=latn";

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

将以下行添加到 Transliterate 类来实例化 OkHttpClientAdd this line to the Transliterate 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 transliteration.

// 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\": \"こんにちは\"\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 {
        Transliterate transliterateRequest = new Transliterate();
        String response = transliterateRequest.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

[
  {
    "text": "konnichiwa",
    "script": "latn"
  }
]

后续步骤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: Transliterate.

let options = {
    method: 'POST',
    baseUrl: endpoint,
    url: 'transliterate',
    qs: {
      'api-version': '3.0',
      'language': 'ja',
      'fromScript': 'jpan',
      'toScript': 'latn'
    },
    headers: {
      'Ocp-Apim-Subscription-Key': subscriptionKey,
      'Content-type': 'application/json',
      'X-ClientTraceId': uuidv4().toString()
    },
    body: [{
          'text': 'こんにちは'
    }],
    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 transliterate-text.js

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

示例响应Sample response

[
    {
        "script": "latn",
        "text": "konnichiwa"
    }
]

清理资源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 或编辑器创建一个新项目,或者在桌面上创建一个包含名为 transliterate-text.py 的文件的新文件夹。Create a new project using your favorite IDE or editor, or a new folder with a file named transliterate-text.py on your desktop. 然后将以下代码片段复制到项目/文件中:Then copy this code snippet into your project/file:

# -*- 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 设置 transliterate 路由并确定我们需使用 API 的版本 3。path sets the transliterate route and identifies that we want to hit version 3 of the API.

params 用于设置输入语言以及输入和输出脚本。The params are used to set the input language, and the input and output scripts. 在此示例中,我们从日语直译为拉丁字母。In this sample, we're transliterating from Japanese to the Latin alphabet.

备注

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

path = '/transliterate?api-version=3.0'
params = '&language=ja&fromScript=jpan&toScript=latn'
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 transliterate text

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

# Transliterate "good afternoon" from source Japanese.
# Note: You can pass more than one object in body.
body = [{
    'text': 'こんにちは'
}]

接下来,请使用 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 transliterate-text.py

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

示例响应Sample response

[
    {
        "script": "latn",
        "text": "konnichiwa"
    }
]

清理资源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