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

快速入门:Translator 入门Quickstart: Get started with Translator

本快速入门介绍如何通过 REST 使用 Translator 服务。In this quickstart, you learn to use the Translator service via REST. 你将从基本示例开始,逐步完成在开发过程中常用的一些核心配置选项,其中包括:You start with basic examples and move onto some core configuration options that are commonly used during development, including:

先决条件Prerequisites

  • Azure 订阅 - 免费创建订阅Azure subscription - Create one for free
  • 有了 Azure 订阅后,请在 Azure 门户中创建 Translator 资源,以获取密钥和终结点。Once you have an Azure subscription, create a Translator resource in the Azure portal to get your key and endpoint. 部署后,选择”转到资源”。After it deploys, select Go to resource.
    • 你需要从资源获取密钥和终结点,以便将应用程序连接到 Translator 服务。You'll need the key and endpoint from the resource to connect your application to the Translator service. 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。You'll paste your key and endpoint into the code below later in the quickstart.
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。You can use the free pricing tier (F0) to try the service, and upgrade later to a paid tier for production.

平台设置Platform setup

  • 创建一个新项目:dotnet new console -o your_project_nameCreate a new project: dotnet new console -o your_project_name
  • 将 Program.cs 替换为下面所示的 C# 代码。Replace Program.cs with the C# code shown below.
  • 在 Program.cs 中设置订阅密钥和终结点值。Set the subscription key and endpoint values in Program.cs.
  • 使用 .NET CLI 添加 Newtonsoft.JsonAdd Newtonsoft.Json using .NET CLI.
  • 从项目目录中运行程序:dotnet runRun the program from the project directory: dotnet run

标头Headers

通过 REST 调用 Translator 服务时,需要确保每个请求中都包含以下标头。When calling the Translator service via REST, you'll need to make sure the following headers are included with each request. 别担心,我们会在以下部分的示例代码中包括标头。Don't worry, we'll include the headers in the sample code in the following sections.

标头Headers 说明Description
身份验证标头Authentication header(s) 必需的请求标头。Required request header.
Ocp-Apim-Subscription-Key

使用认知服务资源时所需的请求头。如果使用翻译器资源,则此为可选。Required request header if using a Cognitive Services Resource. Optional if using a Translator Resource..
Ocp-Apim-Subscription-Region

请参阅用于身份验证的可用选项See available options for authentication.
Content-TypeContent-Type 必需的请求标头。Required request header.
指定有效负载的内容类型。Specifies the content type of the payload.
接受的值为:application/json; charset=UTF-8Accepted value is application/json; charset=UTF-8.
Content-LengthContent-Length 必需的请求标头。Required request header.
请求正文的长度。The length of the request body.
X-ClientTraceIdX-ClientTraceId 可选。Optional.
客户端生成的 GUID,用于唯一标识请求。A client-generated GUID to uniquely identify the request. 如果在查询字符串中使用名为 ClientTraceId 的查询参数包括了跟踪 ID,则可以省略此标头。You can omit this header if you include the trace ID in the query string using a query parameter named ClientTraceId.

密钥和终结点Keys and endpoints

为简单起见,此页面上的示例使用了硬编码的密钥和终结点。The samples on this page use hard-coded keys and endpoints for simplicity. 请记住 完成后将密钥从代码中删除永远不要公开发布该密钥Remember to remove the key from your code when you're done, and never post it publicly. 对于生产环境,请考虑使用安全的方法来存储和访问凭据。For production, consider using a secure way of storing and accessing your credentials. 有关详细信息,请参阅认知服务安全性文章。See the Cognitive Services security article for more information.

翻译文本Translate text

Translator 服务的核心操作是翻译文本。The core operation of the Translator service is to translate text. 在本部分,你将生成一个请求,该请求采用单个源 (from) 并提供两个输出 (to)。In this section, you'll build a request that takes a single source (from) and provides two outputs (to). 然后,我们将查看一些参数,这些参数可用于调整请求和响应。Then we'll review some parameters that can be used to adjust both the request and the response.

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

class Program
{
    private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";

    // Add your location, also known as region. The default is global.
    // This is required if using a Cognitive Services resource.
    private static readonly string location = "YOUR_RESOURCE_LOCATION";
    
    static async Task Main(string[] args)
    {
        // Input and output languages are defined as parameters.
        string route = "/translate?api-version=3.0&from=en&to=de&to=it";
        string textToTranslate = "Hello, world!";
        object[] body = new object[] { new { Text = textToTranslate } };
        var requestBody = JsonConvert.SerializeObject(body);
    
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);
    
            // 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();
            Console.WriteLine(result);
        }
    }
}

成功调用后,应会看到以下响应:After a successful call, you should see the following response:

[
    {
        "translations": [
            {
                "text": "Hallo Welt!",
                "to": "de"
            },
            {
                "text": "Salve, mondo!",
                "to": "it"
            }
        ]
    }
]

检测语言Detect language

如果你知道你需要翻译,但不知道将发送到 Translator 服务的文本的语言,则可以使用语言检测操作。If you know that you'll need translation, but don't know the language of the text that will be sent to the Translator service, you can use the language detection operation. 可以通过多种方式来识别源文本语言。There's more than one way to identify the source text language. 本部分介绍如何通过 translate 终结点和 detect 终结点来使用语言检测。In this section, you'll learn how to use language detection using the translate endpoint, and the detect endpoint.

在翻译过程中检测源语言Detect source language during translation

如果未在翻译请求中包含 from 参数,则 Translator 服务会尝试检测源文本的语言。If you don't include the from parameter in your translation request, the Translator service will attempt to detect the source text's language. 在响应中,你将获得检测到的语言 (language) 和置信度分数 (score)。In the response, you'll get the detected language (language) and a confidence score (score). score 越接近 1.0,意味着检测结果正确的置信度越高。The closer the score is to 1.0, means that there is increased confidence that the detection is correct.

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

class Program
{
    private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";

    // Add your location, also known as region. The default is global.
    // This is required if using a Cognitive Services resource.
    private static readonly string location = "YOUR_RESOURCE_LOCATION";
    
    static async Task Main(string[] args)
    {
        // Output languages are defined as parameters, input language detected.
        string route = "/translate?api-version=3.0&to=de&to=it";
        string textToTranslate = "Hello, world!";
        object[] body = new object[] { new { Text = textToTranslate } };
        var requestBody = JsonConvert.SerializeObject(body);
    
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);
    
            // 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();
            Console.WriteLine(result);
        }
    }
}

成功调用后,应会看到以下响应:After a successful call, you should see the following response:

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

在不进行翻译的情况下检测源语言Detect source language without translation

可以使用 Translator 服务来检测源文本的语言,而不进行翻译。It's possible to use the Translator service to detect the language of source text without performing a translation. 为此,需要使用 /detect 终结点。To do this, you'll use the /detect endpoint.

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

class Program
{
    private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";

    // Add your location, also known as region. The default is global.
    // This is required if using a Cognitive Services resource.
    private static readonly string location = "YOUR_RESOURCE_LOCATION";    
    
    static async Task Main(string[] args)
    {
        // Just detect language
        string route = "/detect?api-version=3.0";
        string textToLangDetect = "Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.";
        object[] body = new object[] { new { Text = textToLangDetect } };
        var requestBody = JsonConvert.SerializeObject(body);
    
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);
    
            // 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();
            Console.WriteLine(result);
        }
    }
}

使用 /detect 终结点时,响应会包括替代检测,并会通知你是否所有检测到的语言都支持翻译和音译。When using the /detect endpoint, the response will include alternate detections, and will let you know if translation and transliteration are supported for all of the detected languages. 成功调用后,应会看到以下响应:After a successful call, you should see the following response:

[
    {
        "alternatives": [
            {
                "isTranslationSupported": true,
                "isTransliterationSupported": false,
                "language": "nl",
                "score": 0.92
            },
            {
                "isTranslationSupported": true,
                "isTransliterationSupported": false,
                "language": "sk",
                "score": 0.77
            }
        ],
        "isTranslationSupported": true,
        "isTransliterationSupported": false,
        "language": "de",
        "score": 1.0
    }
]

直译文本Transliterate text

音译是指基于拼音相似性将脚本(表音符号系统)中的单词或短语从一种语言转换为另一种语言的过程。Transliteration is the process of converting a word or phrase from the script (alphabet) of one language to another based on phonetic similarity. 例如,可以使用音译将“สวัสดี”(thai) 转换为“sawatdi”(latn)。For example, you could use transliteration to convert "สวัสดี" (thai) to "sawatdi" (latn). 可以通过多种方式来执行音译。There's more than one way to perform transliteration. 本部分介绍如何通过 translate 终结点和 transliterate 终结点来使用语言检测。In this section, you'll learn how to use language detection using the translate endpoint, and the transliterate endpoint.

在翻译过程中进行音译Transliterate during translation

如果要翻译成一种使用不同于源的字母表(或音素)的语言,则可能需要使用音译。If you're translating into a language that uses a different alphabet (or phonemes) than your source, you might need a transliteration. 在此示例中,我们将“Hello”从英语翻译为泰语。In this example, we translate "Hello" from English to Thai. 除了获得泰语翻译外,还可以使用拉丁字母获得翻译的短语的音译。In addition to getting the translation in Thai, you'll get a transliteration of the translated phrase using the Latin alphabet.

若要从 translate 终结点获取音译,请使用 toScript 参数。To get a transliteration from the translate endpoint, use the toScript parameter.

备注

有关可用语言和音译选项的完整列表,请参阅语言支持For a complete list of available languages and transliteration options, see language support.

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

class Program
{
    private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";

    // Add your location, also known as region. The default is global.
    // This is required if using a Cognitive Services resource.
    private static readonly string location = "YOUR_RESOURCE_LOCATION";    
    
    static async Task Main(string[] args)
    {
        // Output language defined as parameter, with toScript set to latn
        string route = "/translate?api-version=3.0&to=th&toScript=latn";
        string textToTransliterate = "Hello";
        object[] body = new object[] { new { Text = textToTransliterate } };
        var requestBody = JsonConvert.SerializeObject(body);
    
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);
    
            // 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();
            Console.WriteLine(result);
        }
    }
}

成功调用后,应会看到以下响应。After a successful call, you should see the following response. 请记住,translate 终结点的响应包含检测到的源语言和一个置信度分数、使用输出语言的字母表的翻译,以及使用拉丁字母的音译。Keep in mind that the response from translate endpoint includes the detected source language with a confidence score, a translation using the alphabet of the output language, and a transliteration using the Latin alphabet.

[
    {
        "detectedLanguage": {
            "language": "en",
            "score": 1.0
        },
        "translations": [
            {
                "text": "สวัสดี",
                "to": "th",
                "transliteration": {
                    "script": "Latn",
                    "text": "sawatdi"
                }
            }
        ]
    }
]

在无翻译的情况下进行音译Transliterate without translation

你还可以使用 transliterate 终结点来获取音译。You can also use the transliterate endpoint to get a transliteration. 使用音译终结点时,必须提供源语言 (language)、源脚本/字母表 (fromScript) 以及输出脚本/字母表 (toScript) 作为参数。When using the transliteration endpoint, you must provide the source language (language), the source script/alphabet (fromScript), and the output script/alphabet (toScript) as parameters. 在此示例中,我们将获取 สวัสดี 的音译。In this example, we're going to get the transliteration for สวัสดี.

备注

有关可用语言和音译选项的完整列表,请参阅语言支持For a complete list of available languages and transliteration options, see language support.

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

class Program
{
    private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";

    // Add your location, also known as region. The default is global.
    // This is required if using a Cognitive Services resource.
    private static readonly string location = "YOUR_RESOURCE_LOCATION";   
    
    static async Task Main(string[] args)
    {
        // For a complete list of options, see API reference.
        // Input and output languages are defined as parameters.
        string route = "/translate?api-version=3.0&to=th&toScript=latn";
        string textToTransliterate = "Hello";
        object[] body = new object[] { new { Text = textToTransliterate } };
        var requestBody = JsonConvert.SerializeObject(body);
    
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);
    
            // 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();
            Console.WriteLine(result);
        }
    }
}

成功调用后,应会看到以下响应。After a successful call, you should see the following response. 与对 translate 终结点的调用不同,transliterate 只返回 script 和输出 textUnlike the call to the translate endpoint, transliterate only returns the script and the output text.

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

获取句子长度Get sentence length

使用 Translator 服务,你可以获取一个句子或一系列句子的字符计数。With the Translator service, you can get the character count for a sentence or series of sentences. 响应以数组的形式返回,包含检测到的每个句子的字符计数。The response is returned as an array, with character counts for each sentence detected. 可以通过 translatebreaksentence 终结点获取句子长度。You can get sentence lengths with the translate and breaksentence endpoints.

在翻译过程中获取句子长度Get sentence length during translation

可以使用 translate 终结点获取源文本和翻译输出的字符计数。You can get character counts for both source text and translation output using the translate endpoint. 若要返回句子长度(srcSenLentransSenLen),必须将 includeSentenceLength 参数设置为 TrueTo return sentence length (srcSenLen and transSenLen) you must set the includeSentenceLength parameter to True.

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

class Program
{
    private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";

    // Add your location, also known as region. The default is global.
    // This is required if using a Cognitive Services resource.
    private static readonly string location = "YOUR_RESOURCE_LOCATION";   
    
    static async Task Main(string[] args)
    {
        // Include sentence length details.
        string route = "/translate?api-version=3.0&to=es&includeSentenceLength=true";
        string sentencesToCount = 
                "Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine.";
        object[] body = new object[] { new { Text = sentencesToCount } };
        var requestBody = JsonConvert.SerializeObject(body);
    
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);
    
            // 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();
            Console.WriteLine(result);
        }
    }
}

成功调用后,应会看到以下响应。After a successful call, you should see the following response. 除了检测到的源语言和翻译以外,还将为源 (srcSentLen) 和翻译 (transSentLen) 的每个检测到的句子获取字符计数。In addition to the detected source language and translation, you'll get character counts for each detected sentence for both the source (srcSentLen) and translation (transSentLen).

[
    {
        "detectedLanguage": {
            "language": "en",
            "score": 1.0
        },
        "translations": [
            {
                "sentLen": {
                    "srcSentLen": [
                        44,
                        21,
                        12
                    ],
                    "transSentLen": [
                        48,
                        18,
                        10
                    ]
                },
                "text": "¿Puedes decirme cómo llegar a la estación Penn? ¿No estás seguro? Está bien.",
                "to": "es"
            }
        ]
    }
]

在不翻译的情况下获取句子长度Get sentence length without translation

Translator 服务还允许使用 breaksentence 终结点请求句子长度,无需翻译。The Translator service also lets you request sentence length without translation using the breaksentence endpoint.

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

class Program
{
    private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";

    // Add your location, also known as region. The default is global.
    // This is required if using a Cognitive Services resource.
    private static readonly string location = "YOUR_RESOURCE_LOCATION";   
    
    static async Task Main(string[] args)
    {
        // Only include sentence length details.
        string route = "/breaksentence?api-version=3.0";
        string sentencesToCount = 
                "Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine.";
        object[] body = new object[] { new { Text = sentencesToCount } };
        var requestBody = JsonConvert.SerializeObject(body);
    
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);
    
            // 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();
            Console.WriteLine(result);
        }
    }
}

成功调用后,应会看到以下响应。After a successful call, you should see the following response. 与对 translate 终结点的调用不同,breaksentence 只返回名为 sentLen 的数组中源文本的字符计数。Unlike the call to the translate endpoint, breaksentence only returns the character counts for the source text in an array called sentLen.

[
    {
        "detectedLanguage": {
            "language": "en",
            "score": 1.0
        },
        "sentLen": [
            44,
            21,
            12
        ]
    }
]

字典查找(替代翻译)Dictionary lookup (alternate translations)

使用终结点,可以获取字词或短语的替代翻译。With the endpoint, you can get alternate translations for a word or phrase. 例如,将单词“shark”从 en 翻译为 es 时,此终结点同时返回“tiburón”和“escualo”。For example, when translating the word "shark" from en to es, this endpoint returns both "tiburón" and "escualo".

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

class Program
{
    private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";

    // Add your location, also known as region. The default is global.
    // This is required if using a Cognitive Services resource.
    private static readonly string location = "YOUR_RESOURCE_LOCATION"; 
    
    static async Task Main(string[] args)
    {
        // See many translation options
        string route = "/dictionary/lookup?api-version=3.0&from=en&to=es";
        string wordToTranslate = "shark";
        object[] body = new object[] { new { Text = wordToTranslate } };
        var requestBody = JsonConvert.SerializeObject(body);
    
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);
    
            // 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();
            Console.WriteLine(result);
        }
    }
}

成功调用后,应会看到以下响应。After a successful call, you should see the following response. 让我们将此分解一下,因为此 JSON 比本文中的一些其他示例更复杂。Let's break this down since the JSON is more complex than some of the other examples in this article. translations 数组包含翻译列表。The translations array includes a list of translations. 此数组中的每个对象都包含置信度分数 (confidence)、为显示给最终用户而优化的文本 (displayTarget)、标准化文本 (normalizedText)、语音的部分 (posTag) 以及有关以前翻译的信息 (backTranslations)。Each object in this array includes a confidence score (confidence), the text optimized for end-user display (displayTarget), the normalized text (normalizedText), the part of speech (posTag), and information about previous translation (backTranslations). 有关响应的详细信息,请参阅字典查找For more information about the response, see Dictionary Lookup

[
    {
        "displaySource": "shark",
        "normalizedSource": "shark",
        "translations": [
            {
                "backTranslations": [
                    {
                        "displayText": "shark",
                        "frequencyCount": 45,
                        "normalizedText": "shark",
                        "numExamples": 0
                    }
                ],
                "confidence": 0.8182,
                "displayTarget": "tiburón",
                "normalizedTarget": "tiburón",
                "posTag": "OTHER",
                "prefixWord": ""
            },
            {
                "backTranslations": [
                    {
                        "displayText": "shark",
                        "frequencyCount": 10,
                        "normalizedText": "shark",
                        "numExamples": 1
                    }
                ],
                "confidence": 0.1818,
                "displayTarget": "escualo",
                "normalizedTarget": "escualo",
                "posTag": "NOUN",
                "prefixWord": ""
            }
        ]
    }
]

字典示例(上下文中的翻译)Dictionary examples (translations in context)

执行字典查找后,可以将源文本和翻译传递到 dictionary/examples 终结点,以获取在句子或短语的上下文中显示这两个字词的示例的列表。After you've performed a dictionary lookup, you can pass the source text and translation to the dictionary/examples endpoint to get a list of examples that show both terms in the context of a sentence or phrase. 在上一示例的基础上进行构建时,你需要将字典查找响应中的 normalizedTextnormalizedTarget 分别用作 texttranslationBuilding on the previous example, you'll use the normalizedText and normalizedTarget from the dictionary lookup response as text and translation respectively. 源语言 (from) 和输出目标 (to) 参数是必需的。The source language (from) and output target (to) parameters are required.

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

class Program
{
    private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";

    // Add your location, also known as region. The default is global.
    // This is required if using a Cognitive Services resource.
    private static readonly string location = "YOUR_RESOURCE_LOCATION"; 
    
    static async Task Main(string[] args)
    {
        // See examples of terms in context
        string route = "/dictionary/examples?api-version=3.0&from=en&to=es";
        object[] body = new object[] { new { Text = "Shark",  Translation = "tiburón" } } ;
        var requestBody = JsonConvert.SerializeObject(body);
    
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);
    
            // 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();
            Console.WriteLine(result);
        }
    }
}

成功调用后,应会看到以下响应。After a successful call, you should see the following response. 有关响应的详细信息,请参阅字典查找For more information about the response, see Dictionary Lookup

[
    {
        "examples": [
            {
                "sourcePrefix": "More than a match for any ",
                "sourceSuffix": ".",
                "sourceTerm": "shark",
                "targetPrefix": "Más que un fósforo para cualquier ",
                "targetSuffix": ".",
                "targetTerm": "tiburón"
            },
            {
                "sourcePrefix": "Same with the mega ",
                "sourceSuffix": ", of course.",
                "sourceTerm": "shark",
                "targetPrefix": "Y con el mega ",
                "targetSuffix": ", por supuesto.",
                "targetTerm": "tiburón"
            },
            {
                "sourcePrefix": "A ",
                "sourceSuffix": " ate it.",
                "sourceTerm": "shark",
                "targetPrefix": "Te la ha comido un ",
                "targetSuffix": ".",
                "targetTerm": "tiburón"
            }
        ],
        "normalizedSource": "shark",
        "normalizedTarget": "tiburón"
    }
]

疑难解答Troubleshooting

Java 用户Java users

如果遇到连接问题,可能是因为你的 SSL 证书已过期。If you're encountering connection issues, it may be that your SSL certificate has expired. 若要解决此问题,请将 DigiCertGlobalRootG2.crt 安装到专用存储中。To resolve this issue, install the DigiCertGlobalRootG2.crt to your private store.

后续步骤Next steps

另请参阅See also