Utilizar APIs do Microsoft Azure AI Translator

Neste guia de procedimentos, irá aprender a utilizar as APIs REST do serviço translator. Comece com exemplos básicos e avance para algumas opções de configuração principais que são frequentemente utilizadas durante o desenvolvimento, incluindo:

Pré-requisitos

  • Subscrição do Azure – Criar uma gratuitamente

  • Um recurso multi-serviço ou Tradutor do Azure AI. Assim que tiver a sua subscrição do Azure, crie um serviço único ou um recurso multi-serviço, no portal do Azure, para obter a sua chave e ponto final. Depois de implementar, selecione Ir para recurso.

  • Pode utilizar o escalão de preço gratuito (F0) para experimentar o serviço e atualizar mais tarde para um escalão pago para produção.

  • Precisa da chave e do ponto final do recurso para ligar a sua aplicação ao serviço Translator. Mais tarde, cole a chave e o ponto final nos exemplos de código. Pode encontrar estes valores na página Chaves de portal do Azure e Ponto Final:

    Captura de ecrã: portal do Azure chaves e página de ponto final.

Importante

Lembre-se de remover a chave do código quando terminar e nunca a publicar publicamente. Para produção, utilize uma forma segura de armazenar e aceder às suas credenciais, como o Azure Key Vault. Para obter mais informações, veja a segurança dos serviços de IA do Azure.

Cabeçalhos

Para chamar o serviço translator através da API REST, tem de se certificar de que os seguintes cabeçalhos estão incluídos em cada pedido. Não se preocupe, incluímos os cabeçalhos no código de exemplo nas secções seguintes.

Cabeçalho Valor Condição
Ocp-Apim-Subscription-Key A sua chave de serviço do Translator do portal do Azure.
  • Necessário
Ocp-Apim-Subscription-Region A região onde o recurso foi criado.
  • Necessário ao utilizar um recurso multi-serviço ou regional (geográfico) do Azure AI, como e.U.A. Oeste.
  • Opcional ao utilizar um Recurso de Tradutor de serviço único.
Tipo de Conteúdo O tipo de conteúdo do payload. O valor aceite é application/json ou charset=UTF-8.
  • Necessário
Comprimento do Conteúdo O comprimento do corpo do pedido .
  • Opcional
X-ClientTraceId Um GUID gerado pelo cliente para identificar exclusivamente o pedido. Pode omitir este cabeçalho se incluir o ID de rastreio na cadeia de consulta com um parâmetro de consulta denominado ClientTraceId.
  • Opcional

Configurar a aplicação

  1. Certifique-se de que tem a versão atual do Visual Studio IDE.

    Dica

    Se não estiver familiarizado com o Visual Studio, experimente o módulo Introdução ao Visual Studio Learn.

  2. Abra o Visual Studio.

  3. Na página Iniciar, selecione Criar um novo projeto.

    Captura de ecrã: janela de início do Visual Studio.

  4. Na página Criar um novo projeto, introduza a consola na caixa de pesquisa. Selecione o modelo Aplicação de Consola e, em seguida, selecione Seguinte.

    Captura de ecrã: a página criar novo projeto do Visual Studio.

  5. Na janela De diálogo Configurar o novo projeto , introduza translator_text_app na caixa Nome do projeto. Deixe a caixa de verificação "Colocar solução e projeto no mesmo diretório" desmarcada e selecione Seguinte.

    Captura de ecrã: a janela de diálogo configurar o novo projeto do Visual Studio.

  6. Na janela de diálogo Informações adicionais , certifique-se de que o .NET 6.0 (suporte a longo prazo) está selecionado. Deixe a caixa de verificação "Não utilizar instruções de nível superior" desmarcada e selecione Criar.

    Captura de ecrã: janela de diálogo informações adicionais do Visual Studio.

Instalar o pacote Newtonsoft.json com NuGet

  1. Clique com o botão direito do rato no projeto translator_quickstart e selecione Gerir Pacotes NuGet... .

    Captura de ecrã a mostrar a caixa de pesquisa do pacote NuGet.

  2. Selecione o separador Procurar e escreva Newtonsoft.

    Captura de ecrã a mostrar a janela de instalação do pacote NuGet.

  3. Selecione instalar a partir da janela do gestor de pacotes certa para adicionar o pacote ao seu projeto.

    Captura de ecrã a mostrar o botão de instalação do pacote NuGet.

Compilar a aplicação

Nota

  • A partir do .NET 6, os novos projetos que utilizam o console modelo geram um novo estilo de programa que difere das versões anteriores.
  • A nova saída utiliza funcionalidades C# recentes que simplificam o código de que precisa para escrever.
  • Quando utiliza a versão mais recente, só precisa de escrever o corpo do Main método. Não precisa de incluir instruções de nível superior, diretivas de utilização global ou diretivas de utilização implícita.
  • Para obter mais informações, vejaNew C# templates generate top-level statements (Novos modelos C# geram instruções de nível superior).
  1. Abra o ficheiro Program.cs .

  2. Elimine o código pré-existente, incluindo a linha Console.WriteLine("Hello World!"). Copie e cole os exemplos de código no ficheiro Program.cs da sua aplicação. Para cada exemplo de código, certifique-se de que atualiza as variáveis de chave e ponto final com valores da sua instância do portal do Azure Translator.

  3. Depois de adicionar um exemplo de código pretendido à sua aplicação, selecione o botão de início verde junto a formRecognizer_quickstart para compilar e executar o programa ou prima F5.

Captura de ecrã a mostrar o botão executar programa no Visual Studio.

Importante

Os exemplos neste guia requerem chaves e pontos finais hard-coded. Lembre-se de remover a chave do código quando terminar e nunca a publicar publicamente. Para produção, considere utilizar uma forma segura de armazenar e aceder às suas credenciais. Para obter mais informações, vejaSegurança dos serviços de IA do Azure.

Traduzir texto

A principal operação do serviço translator é traduzir texto. Nesta secção, vai criar um pedido que utiliza uma única origem (from) e fornece duas saídas (to). Em seguida, analisamos alguns parâmetros que podem ser utilizados para ajustar o pedido e a resposta.

using System.Text;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
    // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    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=sw&to=it";
        string textToTranslate = "Hello, friend! What did you do today?";
        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", key);
            // location required if you're using a multi-service or regional (not global) resource.
            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);
        }
    }
}

Após uma chamada bem-sucedida, deverá ver a seguinte resposta:

[
   {
      "translations":[
         {
            "text":"Halo, rafiki! Ulifanya nini leo?",
            "to":"sw"
         },
         {
            "text":"Ciao, amico! Cosa hai fatto oggi?",
            "to":"it"
         }
      ]
   }
]

Pode verificar o consumo (o número de carateres cobrados) para cada pedido nos cabeçalhos de resposta: campo x-metered-usage .

Detetar Idioma

Se precisar de tradução, mas não souber o idioma do texto, pode utilizar a operação de deteção de idioma. Existe mais do que uma forma de identificar o idioma de texto de origem. Nesta secção, vai aprender a utilizar a deteção de idioma com o translate ponto final e o detect ponto final.

Detetar o idioma de origem durante a tradução

Se não incluir o from parâmetro no seu pedido de tradução, o serviço Tradutor tenta detetar o idioma do texto de origem. Na resposta, obtém o idioma detetado (language) e uma classificação de confiança (score). Quanto mais próximo estiver score1.0de , significa que há uma maior confiança de que a deteção está correta.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    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=en&to=it";
        string textToTranslate = "Halo, rafiki! Ulifanya nini leo?";
        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");
            // location required if you're using a multi-service or regional (not global) resource. 
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            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);
        }
    }
}

Após uma chamada bem-sucedida, deverá ver a seguinte resposta:

[
   {
      "detectedLanguage":{
         "language":"sw",
         "score":0.8
      },
      "translations":[
         {
            "text":"Hello friend! What did you do today?",
            "to":"en"
         },
         {
            "text":"Ciao amico! Cosa hai fatto oggi?",
            "to":"it"
         }
      ]
   }
]

Detetar o idioma de origem sem tradução

É possível utilizar o serviço Tradutor para detetar o idioma do texto de origem sem efetuar uma tradução. Para tal, utilize o /detect ponto final.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    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 = "Hallo Freund! Was hast du heute gemacht?";
        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", key);
            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);
        }
    }
}

A /detect resposta do ponto final inclui deteções alternativas e indica se a tradução e a transliteração são suportadas para todos os idiomas detetados. Após uma chamada bem-sucedida, deverá ver a seguinte resposta:

[
   {
      "language":"de",

      "score":1.0,

      "isTranslationSupported":true,

      "isTransliterationSupported":false
   }
]

Transliterar texto

A transliteração é o processo de conversão de uma palavra ou expressão do script (alfabeto) de um idioma para outro com base na semelhança fonética. Por exemplo, pode utilizar a transliteração para converter "สวัสดี" (thai) em "sawatdi" (latn). Existe mais do que uma forma de realizar a transliteração. Nesta secção, vai aprender a utilizar a deteção de idioma com o translate ponto final e o transliterate ponto final.

Transliterar durante a tradução

Se estiver a traduzir para um idioma que utiliza um alfabeto diferente (ou fonemes) do que a sua origem, poderá precisar de uma transliteração. Neste exemplo, vamos traduzir "Hello" de inglês para tailandês. Além de obter a tradução em tailandês, obtém-se uma transliteração da expressão traduzida com o alfabeto latino.

Para obter uma transliteração a translate partir do ponto final, utilize o toScript parâmetro .

Nota

Para obter uma lista completa dos idiomas disponíveis e das opções de transliteração, veja Suporte de idiomas.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    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, friend! What did you do today?";
        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", key);
            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);
        }
    }
}

Após uma chamada bem-sucedida, deverá ver a seguinte resposta. Tenha em atenção que a resposta do ponto final inclui o idioma de translate origem detetado com uma classificação de confiança, uma tradução com o alfabeto da linguagem de saída e uma transliteração com o alfabeto latino.

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1
    },
    "translations": [
      {
        "text": "หวัดดีเพื่อน! วันนี้เธอทำอะไรไปบ้าง ",
        "to": "th",
        "transliteration": {
          "script": "Latn",
          "text": "watdiphuean! wannithoethamaraipaiang"
        }
      }
    ]
  }
]

Transliterar sem tradução

Também pode utilizar o transliterate ponto final para obter uma transliteração. Ao utilizar o ponto final de transliteração, tem de fornecer o idioma de origem (language), o script/alfabeto de origem (fromScript) e o script/alfabeto de saída (toScript) como parâmetros. Neste exemplo, vamos obter a transliteração para สวัสดีเพื่อน! วันนี้คุณทำอะไร.

Nota

Para obter uma lista completa dos idiomas disponíveis e das opções de transliteração, veja Suporte de idiomas.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    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 = "/transliterate?api-version=3.0&language=th&fromScript=thai&toScript=latn";
        string textToTransliterate = "สวัสดีเพื่อน! วันนี้คุณทำอะไร";
        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", key);
            // location required if you're using a multi-service or regional (not global) resource.
            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);
        }
    }
}

Após uma chamada bem-sucedida, deverá ver a seguinte resposta. Ao contrário da chamada para o translate ponto final, transliterate devolve apenas o text resultado e script.

[
   {
      "text":"sawatdiphuean! wannikhunthamarai",

      "script":"latn"
   }
]

Obter o comprimento da frase

Com o serviço Tradutor, pode obter a contagem de carateres para uma frase ou série de frases. A resposta é devolvida como uma matriz, com contagens de carateres para cada frase detetada. Pode obter o comprimento das frases com os translate pontos finais e breaksentence .

Obter o comprimento da frase durante a tradução

Pode obter contagens de carateres para texto de origem e saída de tradução com o translate ponto final. Para devolver o comprimento da frase (srcSenLen e transSenLen) tem de definir o includeSentenceLength parâmetro como True.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    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", key);
            // location required if you're using a multi-service or regional (not global) resource.
            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);
        }
    }
}

Após uma chamada bem-sucedida, deverá ver a seguinte resposta. Além do idioma de origem e da tradução detetados, obtém contagens de carateres para cada frase detetada para a origem (srcSentLen) e tradução (transSentLen).

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

Obter o comprimento da frase sem tradução

O serviço Tradutor também lhe permite pedir o comprimento da frase sem tradução através do breaksentence ponto final.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    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", key);
            // location required if you're using a multi-service or regional (not global) resource.
            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);
        }
    }
}

Após uma chamada bem-sucedida, deverá ver a seguinte resposta. Ao contrário da chamada para o translate ponto final, breaksentence devolve apenas as contagens de carateres para o texto de origem numa matriz chamada sentLen.

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

Pesquisa no dicionário (traduções alternativas)

Com o ponto final, pode obter traduções alternativas para uma palavra ou expressão. Por exemplo, ao traduzir a palavra "raio de sol" de en para es, este ponto final devolve "luz solar", "rayos solares" e "soleamiento", "sol" e "insolación".

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    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 = "sunlight";
        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", key);
            // location required if you're using a multi-service or regional (not global) resource.
            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);
        }
    }
}

Após uma chamada bem-sucedida, deverá ver a seguinte resposta. Vamos examinar a resposta mais detalhadamente, uma vez que o JSON é mais complexo do que alguns dos outros exemplos neste artigo. A translations matriz inclui uma lista de traduções. Cada objeto nesta matriz inclui uma classificação de confiança (confidence), o texto otimizado para apresentação do utilizador final (displayTarget), o texto normalizado (normalizedText), a parte da voz (posTag) e informações sobre a tradução anterior (backTranslations). Para obter mais informações sobre a resposta, veja Pesquisa no Dicionário

[
   {
      "normalizedSource":"sunlight",
      "displaySource":"sunlight",
      "translations":[
         {
            "normalizedTarget":"luz solar",
            "displayTarget":"luz solar",
            "posTag":"NOUN",
            "confidence":0.5313,
            "prefixWord":"",
            "backTranslations":[
               {
                  "normalizedText":"sunlight",
                  "displayText":"sunlight",
                  "numExamples":15,
                  "frequencyCount":702
               },
               {
                  "normalizedText":"sunshine",
                  "displayText":"sunshine",
                  "numExamples":7,
                  "frequencyCount":27
               },
               {
                  "normalizedText":"daylight",
                  "displayText":"daylight",
                  "numExamples":4,
                  "frequencyCount":17
               }
            ]
         },
         {
            "normalizedTarget":"rayos solares",
            "displayTarget":"rayos solares",
            "posTag":"NOUN",
            "confidence":0.1544,
            "prefixWord":"",
            "backTranslations":[
               {
                  "normalizedText":"sunlight",
                  "displayText":"sunlight",
                  "numExamples":4,
                  "frequencyCount":38
               },
               {
                  "normalizedText":"rays",
                  "displayText":"rays",
                  "numExamples":11,
                  "frequencyCount":30
               },
               {
                  "normalizedText":"sunrays",
                  "displayText":"sunrays",
                  "numExamples":0,
                  "frequencyCount":6
               },
               {
                  "normalizedText":"sunbeams",
                  "displayText":"sunbeams",
                  "numExamples":0,
                  "frequencyCount":4
               }
            ]
         },
         {
            "normalizedTarget":"soleamiento",
            "displayTarget":"soleamiento",
            "posTag":"NOUN",
            "confidence":0.1264,
            "prefixWord":"",
            "backTranslations":[
               {
                  "normalizedText":"sunlight",
                  "displayText":"sunlight",
                  "numExamples":0,
                  "frequencyCount":7
               }
            ]
         },
         {
            "normalizedTarget":"sol",
            "displayTarget":"sol",
            "posTag":"NOUN",
            "confidence":0.1239,
            "prefixWord":"",
            "backTranslations":[
               {
                  "normalizedText":"sun",
                  "displayText":"sun",
                  "numExamples":15,
                  "frequencyCount":20387
               },
               {
                  "normalizedText":"sunshine",
                  "displayText":"sunshine",
                  "numExamples":15,
                  "frequencyCount":1439
               },
               {
                  "normalizedText":"sunny",
                  "displayText":"sunny",
                  "numExamples":15,
                  "frequencyCount":265
               },
               {
                  "normalizedText":"sunlight",
                  "displayText":"sunlight",
                  "numExamples":15,
                  "frequencyCount":242
               }
            ]
         },
         {
            "normalizedTarget":"insolación",
            "displayTarget":"insolación",
            "posTag":"NOUN",
            "confidence":0.064,
            "prefixWord":"",
            "backTranslations":[
               {
                  "normalizedText":"heat stroke",
                  "displayText":"heat stroke",
                  "numExamples":3,
                  "frequencyCount":67
               },
               {
                  "normalizedText":"insolation",
                  "displayText":"insolation",
                  "numExamples":1,
                  "frequencyCount":55
               },
               {
                  "normalizedText":"sunstroke",
                  "displayText":"sunstroke",
                  "numExamples":2,
                  "frequencyCount":31
               },
               {
                  "normalizedText":"sunlight",
                  "displayText":"sunlight",
                  "numExamples":0,
                  "frequencyCount":12
               },
               {
                  "normalizedText":"solarization",
                  "displayText":"solarization",
                  "numExamples":0,
                  "frequencyCount":7
               },
               {
                  "normalizedText":"sunning",
                  "displayText":"sunning",
                  "numExamples":1,
                  "frequencyCount":7
               }
            ]
         }
      ]
   }
]

Exemplos de dicionário (traduções no contexto)

Depois de efetuar uma pesquisa no dicionário, transmita o texto de origem e tradução para o dictionary/examples ponto final para obter uma lista de exemplos que mostram ambos os termos no contexto de uma frase ou expressão. Com base no exemplo anterior, utiliza a normalizedText resposta e normalizedTarget a partir da resposta de pesquisa do dicionário como text e translation respetivamente. Os parâmetros de idioma de origem (from) e destino de saída (to) são necessários.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    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 = "sunlight",  Translation = "luz solar" } } ;
        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", key);
            // location required if you're using a multi-service or regional (not global) resource.
            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);
        }
    }
}

Após uma chamada bem-sucedida, deverá ver a seguinte resposta. Para obter mais informações sobre a resposta, veja Pesquisa no Dicionário

[
   {
      "normalizedSource":"sunlight",
      "normalizedTarget":"luz solar",
      "examples":[
         {
            "sourcePrefix":"You use a stake, silver, or ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Se usa una estaca, plata, o ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"A pocket of ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Una bolsa de ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"There must also be ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"También debe haber ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"We were living off of current ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Estábamos viviendo de la ",
            "targetTerm":"luz solar",
            "targetSuffix":" actual."
         },
         {
            "sourcePrefix":"And they don't need unbroken ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Y ellos no necesitan ",
            "targetTerm":"luz solar",
            "targetSuffix":" ininterrumpida."
         },
         {
            "sourcePrefix":"We have lamps that give the exact equivalent of ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Disponemos de lámparas que dan el equivalente exacto de ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"Plants need water and ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Las plantas necesitan agua y ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"So this requires ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Así que esto requiere ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"And this pocket of ",
            "sourceTerm":"sunlight",
            "sourceSuffix":" freed humans from their ...",
            "targetPrefix":"Y esta bolsa de ",
            "targetTerm":"luz solar",
            "targetSuffix":", liberó a los humanos de ..."
         },
         {
            "sourcePrefix":"Since there is no ",
            "sourceTerm":"sunlight",
            "sourceSuffix":", the air within ...",
            "targetPrefix":"Como no hay ",
            "targetTerm":"luz solar",
            "targetSuffix":", el aire atrapado en ..."
         },
         {
            "sourcePrefix":"The ",
            "sourceTerm":"sunlight",
            "sourceSuffix":" shining through the glass creates a ...",
            "targetPrefix":"La ",
            "targetTerm":"luz solar",
            "targetSuffix":" a través de la vidriera crea una ..."
         },
         {
            "sourcePrefix":"Less ice reflects less ",
            "sourceTerm":"sunlight",
            "sourceSuffix":", and more open ocean ...",
            "targetPrefix":"Menos hielo refleja menos ",
            "targetTerm":"luz solar",
            "targetSuffix":", y más mar abierto ..."
         },
         {
            "sourcePrefix":"",
            "sourceTerm":"Sunlight",
            "sourceSuffix":" is most intense at midday, so ...",
            "targetPrefix":"La ",
            "targetTerm":"luz solar",
            "targetSuffix":" es más intensa al mediodía, por lo que ..."
         },
         {
            "sourcePrefix":"... capture huge amounts of ",
            "sourceTerm":"sunlight",
            "sourceSuffix":", so fueling their growth.",
            "targetPrefix":"... capturan enormes cantidades de ",
            "targetTerm":"luz solar",
            "targetSuffix":" que favorecen su crecimiento."
         },
         {
            "sourcePrefix":"... full height, giving more direct ",
            "sourceTerm":"sunlight",
            "sourceSuffix":" in the winter.",
            "targetPrefix":"... altura completa, dando más ",
            "targetTerm":"luz solar",
            "targetSuffix":" directa durante el invierno."
         }
      ]
   }
]

Resolução de problemas

Códigos de estado HTTP comuns

Código de estado de HTTP Descrição Motivo possível
200 OK O pedido foi efetuado com êxito.
400 Pedido Incorreto Um parâmetro necessário está em falta, vazio ou nulo. Em alternativa, o valor transmitido para um parâmetro obrigatório ou opcional é inválido. Um problema comum é um cabeçalho demasiado longo.
401 Não autorizado O pedido não está autorizado. Verifique se a sua chave ou token é válido e na região correta. Veja tambémAutenticação.
429 Demasiados Pedidos Excedeu a quota ou taxa de pedidos permitidos para a sua subscrição.
502 Gateway Inválido Problema do lado da rede ou do servidor. Também pode indicar cabeçalhos inválidos.

Utilizadores java

Se estiver a deparar-se com problemas de ligação, é possível que o certificado TLS/SSL tenha expirado. Para resolver este problema, instale o DigiCertGlobalRootG2.crt no seu arquivo privado.

Passos seguintes