快速入门:使用双语字典查找字词Quickstart: Look up words with bilingual dictionary

本快速入门介绍如何使用“翻译”获取术语的备用翻译,以及这些备用翻译的使用示例。In this quickstart, you'll learn how to get alternate translations for a term, and also usage examples of those alternate translations, using the Translator.

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

第一个命令执行两项操作。The first command does two things. 它创建新的 .NET 控制台应用程序,并创建名为 alternate-sample 的目录。It creates a new .NET console application, and creates a directory named alternate-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

将所需命名空间添加到项目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 Newtonsoft.Json;

从环境变量获取订阅信息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 get alternate translations

Program 类中创建名为 AltTranslation 的函数。Within the Program class, create a function called AltTranslation. 该类封装用于调用 Dictionary 资源的代码,并将结果输出到控制台。This class encapsulates the code used to call the Dictionary resource and prints the result to console.

static void AltTranslation()
{
  /*
   * The code for your call to the translation service will be added to this
   * function in the next few sections.
   */
}

构造 URIConstruct the URI

将以下行添加到 AltTranslation 函数。Add these lines to the AltTranslation function. 你会注意到,除了 api-version 之外,还声明了另外两个参数。You'll notice that along with the api-version, two additional parameters have been declared. 这些参数用于设置翻译的输入和输出。These parameters are used to set the translation input and output. 在此示例中,上述项为英语 (en) 和西班牙语 (es)。In this sample, these are English (en) and Spanish (es).

string route = "/dictionary/lookup?api-version=3.0";
static string params_ = "from=en&to=es";
static string uri = endpoint + path + params_;

接下来需创建 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 array.

System.Object[] body = new System.Object[] { new { Text = @"Elephants" } };
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:

// Set the method to POST
request.Method = HttpMethod.Post;

// Construct the full URI
request.RequestUri = new Uri(uri);

// Add the serialized JSON object to your request
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");

// Add the authorization header
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

// Send request, get response
var response = client.SendAsync(request).Result;
var jsonResponse = response.Content.ReadAsStringAsync().Result;

// Print the response
Console.WriteLine(PrettyPrint(jsonResponse));
Console.WriteLine("Press any key to continue.");

添加 PrettyPrint 以将格式设置添加到 JSON 响应:Add PrettyPrint to add formatting to your JSON response:

static string PrettyPrint(string s)
{
    return JsonConvert.SerializeObject(JsonConvert.DeserializeObject(s), Formatting.Indented);
}

如果使用的是认知服务多服务订阅,则还必须在请求参数中包括 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 函数中调用 AltTranslation()The last step is to call AltTranslation() in the Main function. 找到 static void Main(string[] args) 并添加以下行:Locate static void Main(string[] args) and add these lines:

AltTranslation();
Console.WriteLine("Press any key to continue.");
Console.ReadKey();

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

[
    {
        "displaySource": "elephants",
        "normalizedSource": "elephants",
        "translations": [
            {
                "backTranslations": [
                    {
                        "displayText": "elephants",
                        "frequencyCount": 1207,
                        "normalizedText": "elephants",
                        "numExamples": 5
                    }
                ],
                "confidence": 1.0,
                "displayTarget": "elefantes",
                "normalizedTarget": "elefantes",
                "posTag": "NOUN",
                "prefixWord": ""
            }
        ]
    }
]

清理资源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 / editor or new folder on your desktop. 然后,将此代码片段复制到项目/文件夹的 dictionaryLookup.go 文件中。Then copy this code snippet into your project/folder in a file named dictionaryLookup.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 + "/dictionary/lookup?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.
     */
    dictionaryLookup(subscriptionKey, uri)
}

创建获取备用翻译的函数Create a function to get alternate translations

让我们创建获取备用翻译的函数。Let's create a function to get alternate translations. 此函数将接受一个参数,即“翻译”订阅密钥。This function will take a single argument, your Translator subscription key.

func dictionaryLookup(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 translating from English to Spanish.

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

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

备注

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

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

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

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

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

示例响应Sample response

[
  {
    "displaySource": "pineapples",
    "normalizedSource": "pineapples",
    "translations": [
      {
        "backTranslations": [
          {
            "displayText": "pineapples",
            "frequencyCount": 158,
            "normalizedText": "pineapples",
            "numExamples": 5
          },
          {
            "displayText": "cones",
            "frequencyCount": 13,
            "normalizedText": "cones",
            "numExamples": 5
          },
          {
            "displayText": "piña",
            "frequencyCount": 5,
            "normalizedText": "piña",
            "numExamples": 3
          },
          {
            "displayText": "ganks",
            "frequencyCount": 3,
            "normalizedText": "ganks",
            "numExamples": 2
          }
        ],
        "confidence": 0.7016,
        "displayTarget": "piñas",
        "normalizedTarget": "piñas",
        "posTag": "NOUN",
        "prefixWord": ""
      },
      {
        "backTranslations": [
          {
            "displayText": "pineapples",
            "frequencyCount": 16,
            "normalizedText": "pineapples",
            "numExamples": 2
          }
        ],
        "confidence": 0.2984,
        "displayTarget": "ananás",
        "normalizedTarget": "ananás",
        "posTag": "NOUN",
        "prefixWord": ""
      }
    ]
  }
]

后续步骤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 alt-translation-sample
cd alt-translation-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 = "AltTranslation"
}
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

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

导入所需的库Import required libraries

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

将以下行添加到 AltTranslation 类。Add these lines to the AltTranslation 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 input and output. 在此示例中,上述项为英语 (en) 和西班牙语 (es)。In this sample, these are English (en) and Spanish (es).

private static String subscriptionKey = System.getenv("TRANSLATOR_TEXT_SUBSCRIPTION_KEY");
private static String endpoint = System.getenv("TRANSLATOR_TEXT_ENDPOINT");
String url = endpoint + "/dictionary/lookup?api-version=3.0&from=en&to=es";

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

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

// 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\": \"Pineapples\"\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 {
        AltTranslation altTranslationRequest = new AltTranslation();
        String response = altTranslationRequest.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

[
  {
    "normalizedSource": "pineapples",
    "displaySource": "pineapples",
    "translations": [
      {
        "normalizedTarget": "piñas",
        "displayTarget": "piñas",
        "posTag": "NOUN",
        "confidence": 0.7016,
        "prefixWord": "",
        "backTranslations": [
          {
            "normalizedText": "pineapples",
            "displayText": "pineapples",
            "numExamples": 5,
            "frequencyCount": 158
          },
          {
            "normalizedText": "cones",
            "displayText": "cones",
            "numExamples": 5,
            "frequencyCount": 13
          },
          {
            "normalizedText": "piña",
            "displayText": "piña",
            "numExamples": 3,
            "frequencyCount": 5
          },
          {
            "normalizedText": "ganks",
            "displayText": "ganks",
            "numExamples": 2,
            "frequencyCount": 3
          }
        ]
      },
      {
        "normalizedTarget": "ananás",
        "displayTarget": "ananás",
        "posTag": "NOUN",
        "confidence": 0.2984,
        "prefixWord": "",
        "backTranslations": [
          {
            "normalizedText": "pineapples",
            "displayText": "pineapples",
            "numExamples": 2,
            "frequencyCount": 16
          }
        ]
      }
    ]
  }
]

后续步骤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 或编辑器创建一个新项目,或在桌面上创建新的文件夹。Create a new project using your favorite IDE or editor, or create a new folder on your desktop. 将此代码片段复制到项目/文件夹的 alt-translations.js 文件中。Copy this code snippet into your project/folder into a file named alt-translations.js.

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: Dictionary Lookup.

let options = {
    method: 'POST',
    baseUrl: endpoint,
    url: 'dictionary/lookup',
    qs: {
      'api-version': '3.0',
      'from': 'en',
      'to': 'es'
    },
    headers: {
      'Ocp-Apim-Subscription-Key': subscriptionKey,
      'Content-type': 'application/json',
      'X-ClientTraceId': uuidv4().toString()
    },
    body: [{
          'text': 'Elephants'
    }],
    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 alt-translations.js

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

示例响应Sample response

[
    {
        "displaySource": "elephants",
        "normalizedSource": "elephants",
        "translations": [
            {
                "backTranslations": [
                    {
                        "displayText": "elephants",
                        "frequencyCount": 1207,
                        "normalizedText": "elephants",
                        "numExamples": 5
                    }
                ],
                "confidence": 1.0,
                "displayTarget": "elefantes",
                "normalizedTarget": "elefantes",
                "posTag": "NOUN",
                "prefixWord": ""
            }
        ]
    }
]

清理资源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, or create a new folder on your desktop. 将此代码片段复制到项目/文件夹的 dictionary-lookup.py 文件中。Copy this code snippet into your project/folder into a file named dictionary-lookup.py.

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

params 用于设置源和输出语言。The params are used to set the source and output languages. 在此示例中,我们将使用英语和西班牙语:enesIn this sample we're using English and Spanish: en and es.

备注

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

path = '/dictionary/lookup?api-version=3.0'
params = '&from=en&to=es'
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 find alternate translations

定义要查找其翻译的字符串:Define the string (or strings) that you want to find translations for:

# You can pass more than one object in body.
body = [{
    'text': 'Elephants'
}]

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

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

示例响应Sample response

[
    {
        "displaySource": "elephants",
        "normalizedSource": "elephants",
        "translations": [
            {
                "backTranslations": [
                    {
                        "displayText": "elephants",
                        "frequencyCount": 1207,
                        "normalizedText": "elephants",
                        "numExamples": 5
                    }
                ],
                "confidence": 1.0,
                "displayTarget": "elefantes",
                "normalizedTarget": "elefantes",
                "posTag": "NOUN",
                "prefixWord": ""
            }
        ]
    }
]

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