快速入门:使用“翻译”获取受支持语言的列表Quickstart: Use the Translator to get a list of supported languages

在本快速入门中,请使用“翻译”获取翻译、音译和字典查找支持的语言列表。In this quickstart, you get a list of languages supported for translation, transliteration, and dictionary lookup using 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/.

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

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

dotnet new console -o languages-sample
cd languages-sample

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

将以下行添加到 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 endpoint_var = "TRANSLATOR_TEXT_ENDPOINT";
private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var);

static Program()
{
    if (null == endpoint)
    {
        throw new Exception("Please set/export the environment variable: " + endpoint_var);
    }
}

创建获取语言列表的函数Create a function to get a list of languages

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

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

设置路由Set the route

将以下行添加到 GetLanguages 函数。Add these lines to the GetLanguages function.

string route = "/languages?api-version=3.0";

实例化客户端并发出请求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
  • 添加必需的标头Add required headers
  • 发出异步请求Make an asynchronous request
  • 输出响应Print the response

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

// Set the method to GET
request.Method = HttpMethod.Get;
// Construct the full URI
request.RequestUri = new Uri(endpoint + route);
// Send request, get response
var response = client.SendAsync(request).Result;
var jsonResponse = response.Content.ReadAsStringAsync().Result;
// Pretty print the response
Console.WriteLine(PrettyPrint(jsonResponse));
Console.WriteLine("Press any key to continue.");

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

要使用“Pretty Print”(响应格式)打印响应,请将此函数添加到 Program 类:To print the response with "Pretty Print" (formatting for the response), add this function to your Program class:

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

将其放在一起Put it all together

最后一步是在 Main 函数中调用 GetLanguages()The last step is to call GetLanguages() in the Main function. 找到 static void Main(string[] args) 并添加以下行:Locate static void Main(string[] args) and add these lines:

GetLanguages();
Console.ReadLine();

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

请在此语言列表中查找国家/地区缩写。Find the country/region abbreviation in this list of languages.

{
    "translation": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr"
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl"
        },
        ...
    },
    "transliteration": {
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "scripts": [
                {
                    "code": "Arab",
                    "name": "Arabic",
                    "nativeName": "العربية",
                    "dir": "rtl",
                    "toScripts": [
                        {
                            "code": "Latn",
                            "name": "Latin",
                            "nativeName": "اللاتينية",
                            "dir": "ltr"
                        }
                    ]
                },
                {
                    "code": "Latn",
                    "name": "Latin",
                    "nativeName": "اللاتينية",
                    "dir": "ltr",
                    "toScripts": [
                        {
                            "code": "Arab",
                            "name": "Arabic",
                            "nativeName": "العربية",
                            "dir": "rtl"
                        }
                    ]
                }
            ]
        },
      ...
    },
    "dictionary": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
      ...
    }
}

清理资源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 or new folder on your desktop. 然后,将此代码片段复制到项目/文件夹的 get-languages.go 文件中。Then copy this code snippet into your project/folder in a file named get-languages.go.

package main

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

创建 main 函数Create the main function

让我们为应用程序创建 main 函数。Let's create the main function for our application. 你会注意到,它是单行代码。You'll notice it's a single line of code. 这是因为,我们要创建的单一函数用于为翻译获取和输出受支持语言的列表。That's because we're creating a single function to get and print the list of supported languages for Translator.

此示例将尝试从环境变量 TRANSLATOR_TEXT_ENDPOINT 读取“翻译”终结点。This sample will try to read your Translator endpoint from an environment variable: TRANSLATOR_TEXT_ENDPOINT. 如果不熟悉环境变量,则可将 endpoint 设置为字符串并注释掉条件语句。If you're not familiar with environment variables, you can set endpoint as a string and comment out the conditional statement.

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

func main() {
    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 + "/languages?api-version=3.0"
    getLanguages(uri)
}

创建获取受支持语言列表的函数Create a function to get a list of supported languages

我们来创建获取受支持语言列表的函数。Let's create a function to get a list of supported languages.

func getLanguages(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.

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

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

备注

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

生成请求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 GET request
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
    log.Fatal(err)
}
// Add required headers
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

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

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

示例响应Sample response

请在此语言列表中查找国家/地区缩写。Find the country/region abbreviation in this list of languages.

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

{
  "dictionary": {
    "af": {
      "name": "Afrikaans",
      "nativeName": "Afrikaans",
      "dir": "ltr",
      "translations": [
        {
          "name": "English",
          "nativeName": "English",
          "dir": "ltr",
          "code": "en"
        }
      ]
    },
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "dir": "rtl",
      "translations": [
        {
          "name": "English",
          "nativeName": "English",
          "dir": "ltr",
          "code": "en"
        }
      ]
    },
...
  },
  "translation": {
    "af": {
      "name": "Afrikaans",
      "nativeName": "Afrikaans",
      "dir": "ltr"
    },
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "dir": "rtl"
    },
...
  },
  "transliteration": {
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "scripts": [
        {
          "code": "Arab",
          "name": "Arabic",
          "nativeName": "العربية",
          "dir": "rtl",
          "toScripts": [
            {
              "code": "Latn",
              "name": "Latin",
              "nativeName": "اللاتينية",
              "dir": "ltr"
            }
          ]
        },
        {
          "code": "Latn",
          "name": "Latin",
          "nativeName": "اللاتينية",
          "dir": "ltr",
          "toScripts": [
            {
              "code": "Arab",
              "name": "Arabic",
              "nativeName": "العربية",
              "dir": "rtl"
            }
          ]
        }
      ]
    },
...
  }
}

后续步骤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 get-languages-sample
cd get-languages-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 = "GetLanguages"
}
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

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

导入所需的库Import required libraries

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

将以下行添加到 GetLanguages 类。Add these lines to the GetLanguages class. 你会注意到,将从环境变量中读取订阅密钥和终结点:You'll notice the subscription key and endpoint are being read from environment variables:

private static String subscriptionKey = System.getenv("TRANSLATOR_TEXT_SUBSCRIPTION_KEY");
private static String endpoint = System.getenv("TRANSLATOR_TEXT_ENDPOINT");
String url = endpoint + "/languages?api-version=3.0";

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

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

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

接下来,我们将生成 GET 请求。Next, let's build the GET request.

// This function performs a GET request.
public String Get() throws IOException {
    Request request = new Request.Builder()
            .url(url).get()
            .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 {
        GetLanguages getLanguagesRequest = new GetLanguages();
        String response = getLanguagesRequest.Get();
        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

请在此语言列表中查找国家/地区缩写。Find the country/region abbreviation in this list of languages.

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

{
  "translation": {
    "af": {
      "name": "Afrikaans",
      "nativeName": "Afrikaans",
      "dir": "ltr"
    },
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "dir": "rtl"
    },
...
  },
  "transliteration": {
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "scripts": [
        {
          "code": "Arab",
          "name": "Arabic",
          "nativeName": "العربية",
          "dir": "rtl",
          "toScripts": [
            {
              "code": "Latn",
              "name": "Latin",
              "nativeName": "اللاتينية",
              "dir": "ltr"
            }
          ]
        },
        {
          "code": "Latn",
          "name": "Latin",
          "nativeName": "اللاتينية",
          "dir": "ltr",
          "toScripts": [
            {
              "code": "Arab",
              "name": "Arabic",
              "nativeName": "العربية",
              "dir": "rtl"
            }
          ]
        }
      ]
    },
...
  },
  "dictionary": {
    "af": {
      "name": "Afrikaans",
      "nativeName": "Afrikaans",
      "dir": "ltr",
      "translations": [
        {
          "name": "English",
          "nativeName": "English",
          "dir": "ltr",
          "code": "en"
        }
      ]
    },
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "dir": "rtl",
      "translations": [
        {
          "name": "English",
          "nativeName": "English",
          "dir": "ltr",
          "code": "en"
        }
      ]
    },
...
  }
}

后续步骤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. 然后,将此代码片段复制到项目的名为 get-languages.js 的文件中。Then copy this code snippet into your project in a file named get-languages.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 endpoint

此示例将尝试从环境变量 TRANSLATOR_TEXT_ENDPOINT 读取“翻译”终结点。This sample will try to read your Translator endpoint from an environment variable: TRANSLATOR_TEXT_ENDPOINT. 如果不熟悉环境变量,则可将 endpoint 设置为字符串并注释掉条件语句。If you're not familiar with environment variables, you can set endpoint as a string and comment out the conditional statement.

lorum ipsum

配置请求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: Languages.

let options = {
    method: 'GET',
    baseUrl: endpoint,
    url: 'languages',
    qs: {
      'api-version': '3.0',
    },
    headers: {
      'Content-type': 'application/json',
      'X-ClientTraceId': uuidv4().toString()
    },
    json: true,
};

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

发出请求并输出响应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 get-languages.js

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

示例响应Sample response

请在此语言列表中查找国家/地区缩写。Find the country/region abbreviation in this list of languages.

此示例已截断,显示了结果的片段:This sample has been truncated to show a snippet of the result:

{
    "translation": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr"
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl"
        },
        ...
    },
    "transliteration": {
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "scripts": [
                {
                    "code": "Arab",
                    "name": "Arabic",
                    "nativeName": "العربية",
                    "dir": "rtl",
                    "toScripts": [
                        {
                            "code": "Latn",
                            "name": "Latin",
                            "nativeName": "اللاتينية",
                            "dir": "ltr"
                        }
                    ]
                },
                {
                    "code": "Latn",
                    "name": "Latin",
                    "nativeName": "اللاتينية",
                    "dir": "ltr",
                    "toScripts": [
                        {
                            "code": "Arab",
                            "name": "Arabic",
                            "nativeName": "العربية",
                            "dir": "rtl"
                        }
                    ]
                }
            ]
        },
      ...
    },
    "dictionary": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
      ...
    }
}

清理资源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. 然后,将此代码片段复制到项目的名为 get-languages.py 的文件中。Then copy this code snippet into your project in a file named get-languages.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 endpoint and path

此示例将尝试从环境变量 TRANSLATOR_TEXT_ENDPOINT 读取“翻译”终结点。This sample will try to read your Translator endpoint from an environment variable: TRANSLATOR_TEXT_ENDPOINT. 如果不熟悉环境变量,则可将 endpoint 设置为字符串并注释掉条件语句。If you're not familiar with environment variables, you can set endpoint as a string and comment out the conditional statement.

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

备注

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

path = '/languages?api-version=3.0'
constructed_url = endpoint + path

添加标头Add headers

请求获取支持的语言不需身份验证。The request to get supported languages doesn't require authentication. Content-type 设置为 application/json 并添加 X-ClientTraceId,以便对请求进行唯一标识。Set the Content-type as application/json and add X-ClientTraceId to uniquely identify your request.

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

headers = {
    '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 get a list of supported languages

请使用 requests 模块创建 GET 请求。Let's create a GET request using the requests module. 它使用两个参数:串联的 URL 和请求标头:It takes two arguments: the concatenated URL, and the request headers:

request = requests.get(constructed_url, headers=headers)
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 get-languages.py

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

示例响应Sample response

请在此语言列表中查找国家/地区缩写。Find the country/region abbreviation in this list of languages.

此示例已截断,显示了结果的片段:This sample has been truncated to show a snippet of the result:

{
    "translation": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr"
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl"
        },
        ...
    },
    "transliteration": {
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "scripts": [
                {
                    "code": "Arab",
                    "name": "Arabic",
                    "nativeName": "العربية",
                    "dir": "rtl",
                    "toScripts": [
                        {
                            "code": "Latn",
                            "name": "Latin",
                            "nativeName": "اللاتينية",
                            "dir": "ltr"
                        }
                    ]
                },
                {
                    "code": "Latn",
                    "name": "Latin",
                    "nativeName": "اللاتينية",
                    "dir": "ltr",
                    "toScripts": [
                        {
                            "code": "Arab",
                            "name": "Arabic",
                            "nativeName": "العربية",
                            "dir": "rtl"
                        }
                    ]
                }
            ]
        },
      ...
    },
    "dictionary": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
      ...
    }
}

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