您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

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

本快速入门介绍如何使用文本翻译 API 来确定句子长度。In this quickstart, you'll learn how to determine the length of sentences using the Translator Text API.

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

先决条件Prerequisites

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

设置Set up

创建文本翻译资源Create a Translator Text resource

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

  • 免费获取在 7 天内有效的试用版密钥Get a trial key valid for 7 days for free. 注册之后,它就可以在 Azure 网站上使用了。After signing up, it will be available on the Azure website.
  • 查看 Azure 门户中的现有资源。View an existing resource in the Azure portal.

从试用订阅或资源获取密钥后,创建两个环境变量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 Text resource.
  • TRANSLATOR_TEXT_ENDPOINT - 文本翻译的全局终结点。TRANSLATOR_TEXT_ENDPOINT - The global endpoint for Translator Text. 使用 https://api.cognitive.microsofttranslator.com/Use https://api.cognitive.microsofttranslator.com/.

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

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

dotnet new console -o sentences-sample
cd sentences-sample

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

打开项目,然后打开 sentences-sample.csprojOpen your project, then open sentences-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

接下来,我们将创建一个在反序列化由文本翻译 API 返回的 JSON 响应时使用的类。Next, we're going to create a class that's used when deserializing the JSON response returned by the Translator Text API.

/// <summary>
/// The C# classes that represents the JSON returned by the Translator Text API.
/// </summary>
public class BreakSentenceResult
{
    public int[] SentLen { get; set; }
    public DetectedLanguage DetectedLanguage { get; set; }
}

public class DetectedLanguage
{
    public string Language { get; set; }
    public float Score { 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 determine sentence length

Program 类中,创建一个名为 BreakSentenceRequest() 的新函数。In the Program class, create a new function called BreakSentenceRequest(). 此函数采用四个参数:subscriptionKeyendpointrouteinputTextThis function takes four arguments: subscriptionKey, endpoint, route, and inputText.

static public async Task BreakSentenceRequest(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 break sentence request

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

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.
BreakSentenceResult[] deserializedOutput = JsonConvert.DeserializeObject<BreakSentenceResult[]>(result);
foreach (BreakSentenceResult o in deserializedOutput)
{
    Console.WriteLine("The detected language is '{0}'. Confidence is: {1}.", o.DetectedLanguage.Language, o.DetectedLanguage.Score);
    Console.WriteLine("The first sentence length is: {0}", o.SentLen[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.

将其放在一起Put it all together

最后一步是在 Main 函数中调用 BreakSentenceRequest()The last step is to call BreakSentenceRequest() in the Main function. 找到 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.
    string route = "/breaksentence?api-version=3.0";
    // Feel free to use any string.
    string breakSentenceText = @"How are you doing today? The weather is pretty pleasant. Have you been to the movies lately?";
    await BreakSentenceRequest(subscriptionKey, endpoint, route, breakSentenceText);
    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

你会注意到,在 Main 中声明了 subscriptionKeyendpointroute 以及要评估的文本 breakSentenceTextYou'll notice that in Main, you're declaring subscriptionKey, endpoint, route, and the text to evaluate breakSentenceText.

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

The detected language is \'en\'. Confidence is: 1.
The first sentence length is: 25

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

[
    {
        "detectedLanguage":
        {
            "language":"en",
            "score":1.0
        },
        "sentLen":[25,32,35]
    }
]

清理资源Clean up resources

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

后续步骤Next steps

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

先决条件Prerequisites

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

设置Set up

创建文本翻译资源Create a Translator Text resource

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

  • 免费获取在 7 天内有效的试用版密钥Get a trial key valid for 7 days for free. 注册之后,它就可以在 Azure 网站上使用了。After signing up, it will be available on the Azure website.
  • 查看 Azure 门户中的现有资源。View an existing resource in the Azure portal.

从试用订阅或资源获取密钥后,创建两个环境变量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 Text resource.
  • TRANSLATOR_TEXT_ENDPOINT - 文本翻译的全局终结点。TRANSLATOR_TEXT_ENDPOINT - The global endpoint for Translator Text. 使用 https://api.cognitive.microsofttranslator.com/Use https://api.cognitive.microsofttranslator.com/.

使用 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 length-sentence-sample
cd length-sentence-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 = "BreakSentence"
}
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

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

导入所需的库Import required libraries

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

将以下行添加到 BreakSentence 类。Add these lines to the BreakSentence class. 首先,从环境变量中读取订阅密钥和终结点。First, the subscription key and endpoint are being read from environment variables. 然后,你会注意到,除了 api-version,还可以定义输入语言。Then, you'll notice that along with the api-version, you can define the input language. 在此示例中,语言为英语。In this sample it's English.

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

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

将以下行添加到 BreakSentence 类来实例化 OkHttpClientAdd this line to the BreakSentence 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. 文本必须进行转义。The text must be escaped.

// This function performs a POST request.
public String Post() throws IOException {
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType,
            "[{\n\t\"Text\": \"How are you? I am fine. What did you do today?\"\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 Text 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 {
        BreakSentence breakSentenceRequest = new BreakSentence();
        String response = BreakSentenceRequest.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

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

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

后续步骤Next steps

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

先决条件Prerequisites

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

设置Set up

创建文本翻译资源Create a Translator Text resource

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

  • 免费获取在 7 天内有效的试用版密钥Get a trial key valid for 7 days for free. 注册之后,它就可以在 Azure 网站上使用了。After signing up, it will be available on the Azure website.
  • 查看 Azure 门户中的现有资源。View an existing resource in the Azure portal.

从试用订阅或资源获取密钥后,创建两个环境变量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 Text resource.
  • TRANSLATOR_TEXT_ENDPOINT - 文本翻译的全局终结点。TRANSLATOR_TEXT_ENDPOINT - The global endpoint for Translator Text. 使用 https://api.cognitive.microsofttranslator.com/Use https://api.cognitive.microsofttranslator.com/.

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

使用最喜欢的 IDE 或编辑器创建新的 Python 项目。Create a new Python project using your favorite IDE or editor. 然后,将此代码片段复制到项目的名为 sentence-length.py 的文件中。Then copy this code snippet into your project in a file named sentence-length.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 请求、创建唯一标识符,以及处理文本翻译 API 返回的 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 Text API.

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

此示例将尝试从以下环境变量中读取文本翻译订阅密钥和终结点:TRANSLATOR_TEXT_KEYTRANSLATOR_TEXT_ENDPOINTThis sample will try to read your Translator Text 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 Text global endpoint is set as the endpoint. path 设置 breaksentence 路由并确定我们需使用 API 的版本 3。path sets the breaksentence route and identifies that we want to hit version 3 of the API.

此示例中的 params 用于设置所提供文本的语言。The params in this sample are used to set the language of the provided text. params 不是 breaksentence 路由所需的。params aren't required for the breaksentence route. 如果不包含在请求中,此 API 会尝试检测所提供文本的语言,并会在响应中提供此信息以及置信度分数。If left out of the request, the API will try to detect the language of the provided text, and provide this information along with a confidence score in the response.

备注

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

path = '/breaksentence?api-version=3.0'
params = '&language=en'
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 determine sentence length

定义需要确定其长度的句子:Define the sentence (or sentences) that you want to determine the length of:

# You can pass more than one object in body.
body = [{
    'text': 'How are you? I am fine. What did you do today?'
}]

接下来,请使用 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

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

python sentence-length.py

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

示例响应Sample response

[
    {
        "sentLen": [
            13,
            11,
            22
        ]
    }
]

清理资源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 参考,了解使用文本翻译 API 可以执行的所有操作。Take a look at the API reference to understand everything you can do with the Translator Text API.

先决条件Prerequisites

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

设置Set up

创建文本翻译资源Create a Translator Text resource

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

  • 免费获取在 7 天内有效的试用版密钥Get a trial key valid for 7 days for free. 注册之后,它就可以在 Azure 网站上使用了。After signing up, it will be available on the Azure website.
  • 查看 Azure 门户中的现有资源。View an existing resource in the Azure portal.

从试用订阅或资源获取密钥后,创建两个环境变量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 Text resource.
  • TRANSLATOR_TEXT_ENDPOINT - 文本翻译的全局终结点。TRANSLATOR_TEXT_ENDPOINT - The global endpoint for Translator Text. 使用 https://api.cognitive.microsofttranslator.com/Use https://api.cognitive.microsofttranslator.com/.

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

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

备注

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

let options = {
    method: 'POST',
    baseUrl: endpoint,
    url: 'breaksentence',
    qs: {
      'api-version': '3.0',
    },
    headers: {
      'Ocp-Apim-Subscription-Key': subscriptionKey,
      'Content-type': 'application/json',
      'X-ClientTraceId': uuidv4().toString()
    },
    body: [{
          'text': 'How are you? I am fine. What did you do today?'
    }],
    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

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

node sentence-length.js

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

示例响应Sample response

[
    {
        "sentLen": [
            13,
            11,
            22
        ]
    }
]

清理资源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 参考,了解使用文本翻译 API 可以执行的所有操作。Take a look at the API reference to understand everything you can do with the Translator Text API.

先决条件Prerequisites

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

设置Set up

创建文本翻译资源Create a Translator Text resource

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

  • 免费获取在 7 天内有效的试用版密钥Get a trial key valid for 7 days for free. 注册之后,它就可以在 Azure 网站上使用了。After signing up, it will be available on the Azure website.
  • 查看 Azure 门户中的现有资源。View an existing resource in the Azure portal.

从试用订阅或资源获取密钥后,创建两个环境变量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 Text resource.
  • TRANSLATOR_TEXT_ENDPOINT - 文本翻译的全局终结点。TRANSLATOR_TEXT_ENDPOINT - The global endpoint for Translator Text. 使用 https://api.cognitive.microsofttranslator.com/Use https://api.cognitive.microsofttranslator.com/.

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

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

package main

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

创建 main 函数Create the main function

此示例将尝试从以下环境变量中读取文本翻译订阅密钥和终结点:TRANSLATOR_TEXT_SUBSCRIPTION_KEYTRANSLATOR_TEXT_ENDPOINTThis sample will try to read your Translator Text 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 + "/breaksentence?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.
     */
    breakSentence(subscriptionKey, uri)
}

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

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

func breakSentence(subscriptionKey string, 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.

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

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

备注

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

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

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

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

生成请求Build the request

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

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

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

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

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

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

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

将其放在一起Put it all together

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

go run sentence-length.go

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

示例响应Sample response

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

后续步骤Next steps

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

另请参阅See also