Usare le API Traduttore per Azure AI

In questa guida pratica si apprenderà come usare le API REST del servizio Traduttore. Si inizierà con esempi di base per poi passare ad alcune delle principali opzioni di configurazione comunemente usate durante lo sviluppo, tra cui:

Prerequisiti

  • Sottoscrizione di Azure: creare un account gratuito

  • Una risorsa multiservizio o Traduttore di Azure per intelligenza artificiale. Dopo aver creato la sottoscrizione di Azure, creare una risorsa a servizio singolo o multiservizio nel portale di Azure, per ottenere la chiave e l'endpoint. Al termine della distribuzione, fare clic su Vai alla risorsa.

  • È possibile usare il piano tariffario gratuito (F0) per provare il servizio ed eseguire in un secondo momento l'aggiornamento a un livello a pagamento per la produzione.

  • Per connettere l'applicazione al servizio Traduttore, sono necessari la chiave e l'endpoint della risorsa. Successivamente, incollare la chiave e l'endpoint negli esempi di codice. È possibile trovare questi valori nella pagina Chiavi ed endpoint del portale di Azure:

    Screenshot: Azure portal keys and endpoint page.

Importante

Al termine, ricordarsi di rimuovere la chiave dal codice e non renderlo mai pubblico. Per la produzione, usare un modo sicuro per archiviare e accedere alle credenziali, ad esempio Azure Key Vault. Per altre informazioni, vedereSicurezza di Servizi di Azure AI.

Intestazioni

Per chiamare il servizio Traduttore tramite l'API REST, è necessario assicurarsi che le intestazioni seguenti siano incluse in ogni richiesta. Nel codice di esempio queste intestazioni sono già incluse nelle sezioni seguenti.

Intestazione Valore Condizione
Ocp-Apim-Subscription-Key La chiave del servizio Traduttore dal portale di Azure.
  • Obbligatorio
Ocp-Apim-Subscription-Region Area in cui è stata creata la risorsa.
  • Obbligatorio quando si usa una risorsa multiservizio o area geografica di Azure per intelligenza artificiale, ad esempio Stati Uniti occidentali.
  • Facoltativo quando si usa una risorsa Traduttore a servizio singolo.
Content-Type Tipo di contenuto del payload. Il valore accettato è application/json o charset=UTF-8.
  • Obbligatorio
Content-Length Lunghezza del corpo della richiesta.
  • Facoltativo
X-ClientTraceId GUID generato dal client che identifica in modo univoco la richiesta. È possibile omettere questa intestazione, se nella stringa della query si include l'ID traccia con un parametro di query denominato ClientTraceId.
  • Facoltativo

Configurazione dell'applicazione

  1. Assicurarsi di avere la versione corrente dell'IDE di Visual Studio.

    Suggerimento

    Se non si ha familiarità con Visual Studio, provare il modulo di Learn Introduzione a Visual Studio.

  2. Aprire Visual Studio.

  3. Nella pagina Avvio, scegliere Crea un nuovo progetto.

    Screenshot: Visual Studio start window.

  4. Nella pagina Crea un nuovo progetto immettere console nella casella di ricerca. Scegliere il modello Applicazione console, quindi selezionare Avanti.

    Screenshot: Visual Studio's create new project page.

  5. Nella finestra di dialogo Configura il nuovo progetto, immettere translator_text_app nella casella Nome progetto. Lasciare deselezionata la casella di controllo "Inserisci soluzione e progetto nella stessa directory" e selezionare Avanti.

    Screenshot: Visual Studio's configure new project dialog window.

  6. Nella finestra di dialogo Informazioni aggiuntive, verificare che sia selezionata l'opzione .NET 6.0 (supporto a lungo termine). Lasciare deselezionata la casella di controllo "Non usare istruzioni di primo livello" e selezionare Crea.

    Screenshot: Visual Studio's additional information dialog window.

Installare il pacchetto Newtonsoft.json con NuGet

  1. Fare clic con il pulsante destro del mouse sul progetto translator_quickstart e selezionare Gestisci pacchetti NuGet....

    Screenshot of the NuGet package search box.

  2. Selezionare la scheda Sfoglia e digitare Newtonsoft.

    Screenshot of the NuGet package install window.

  3. Per aggiungere il pacchetto al progetto, selezionare Installa nella corretta finestra di gestione pacchetti.

    Screenshot of the NuGet package install button.

Compilare l'applicazione

Nota

  • A partire da .NET 6, i nuovi progetti che usano il modello console generano un nuovo stile di programma, diverso dalle versioni precedenti.
  • Il nuovo output usa le funzionalità C# recenti che semplificano il codice da scrivere.
  • Quando si usa la versione più recente, è sufficiente scrivere il corpo del metodo Main. Non è necessario includere istruzioni generali, direttive d'uso globali o implicite.
  • Per altre informazioni, vedereNuovi modelli C# generano istruzioni generali.
  1. Aprire il file Program.cs.

  2. Eliminare il codice preesistente, inclusa la riga Console.WriteLine("Hello World!"). Copiare e incollare gli esempi di codice nel file Program.cs dell'applicazione. Per ogni esempio di codice, assicurarsi di aggiornare la chiave e le variabili dell'endpoint con i valori dell'istanza di Traduttore del portale di Azure.

  3. Dopo aver aggiunto un esempio di codice desiderato all'applicazione, scegliere il pulsante di avvio verde accanto a formRecognizer_quickstart per compilare ed eseguire il programma oppure premere F5.

Screenshot of the run program button in Visual Studio.

Importante

Gli esempi in questa guida richiedono chiavi ed endpoint hardcoded. Al termine, ricordarsi di rimuovere la chiave dal codice e non renderlo mai pubblico. Per la produzione, è consigliabile usare un modo sicuro per archiviare e accedere alle credenziali, Per altre informazioni, vedere Sicurezza dei servizi di Azure AI.

Tradurre testo

La funzione principale del servizio Traduttore è tradurre testo. In questa sezione si crea una richiesta che accetta un'unica origine (from) e fornisce due output (to). Si esamineranno quindi alcuni parametri che possono essere usati per modificare sia la richiesta che la risposta.

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);
        }
    }
}

Dopo una chiamata riuscita, si dovrebbe vedere la risposta seguente:

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

È possibile controllare il consumo (il numero di caratteri addebitati) per ogni richiesta nel campo intestazioni della risposta: x-metered-usage.

Rileva lingua

Se è necessaria la traduzione, ma non si conosce la lingua del testo, è possibile usare l'operazione di rilevamento della lingua. È possibile identificare la lingua del testo di origine in più modi. In questa sezione viene illustrato come usare la traslitterazione della lingua tramite l'endpoint translate e l'endpoint detect.

Rilevare la lingua di origine durante la traduzione

Se non si include il parametro from nella richiesta di traduzione, il servizio Traduttore cerca di rilevare la lingua del testo di origine. Nella risposta si ottiene la lingua rilevata (language) e un punteggio di attendibilità (score). Più il valore di score è vicino a 1.0, più aumenta la probabilità che il rilevamento sia corretto.

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);
        }
    }
}

Dopo una chiamata riuscita, si dovrebbe vedere la risposta seguente:

[
   {
      "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"
         }
      ]
   }
]

Rilevare la lingua di origine senza traduzione

È possibile usare il servizio Traduttore per rilevare la lingua del testo di origine senza eseguire una traduzione. A tale scopo, usare l'endpoint /detect.

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);
        }
    }
}

La risposta dell'endpoint /detect include rilevamenti alternativi e indica se la traduzione e la traslitterazione sono supportate per tutte le lingue rilevate. Dopo una chiamata riuscita, si dovrebbe vedere la risposta seguente:

[
   {
      "language":"de",

      "score":1.0,

      "isTranslationSupported":true,

      "isTransliterationSupported":false
   }
]

Traslitterare testo

La traslitterazione è il processo di conversione di una parola o di una frase dall'alfabeto di una lingua a quello di un'altra lingua in base alla somiglianza fonetica. Ad esempio, si potrebbe usare la traslitterazione per convertire "สวัสดี" (thai) in "sawatdi" (latn). È possibile eseguire la traslitterazione in più modi. In questa sezione viene illustrato come usare la traslitterazione della lingua tramite l'endpoint translate e l'endpoint transliterate.

Eseguire la traslitterazione durante la traduzione

Se occorre eseguire la traduzione in una lingua che usa un alfabeto (o fonemi) diverso dalla lingua di origine, potrebbe essere necessaria una traslitterazione. In questo esempio si tradurrà la parola "Hello" dall'inglese al thai. Oltre a ricevere la traduzione in thailandese, si ottiene una traslitterazione della parola tradotta usando l'alfabeto latino.

Per ottenere una traslitterazione dall'endpoint translate, usare il parametro toScript.

Nota

Per un elenco completo delle lingue e delle opzioni di traslitterazione disponibili, vedere Lingue supportate.

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);
        }
    }
}

Dopo una chiamata riuscita, si dovrebbe vedere la risposta seguente. Tenere presente che la risposta dell'endpoint translate include la lingua di origine rilevata con un punteggio di attendibilità, una traduzione con l'alfabeto della lingua di output e una traslitterazione con l'alfabeto latino.

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

Eseguire la traslitterazione senza traduzione

Si può anche usare l'endpoint transliterate per ottenere una traslitterazione. Quando si usa l'endpoint di traslitterazione, è necessario specificare la lingua di origine (language), l'alfabeto di origine (fromScript) e l'alfabeto di output (toScript) come parametri. In questo esempio si otterrà la traslitterazione di สวัสดีเพื่อน! วันนี้คุณทำอะไร.

Nota

Per un elenco completo delle lingue e delle opzioni di traslitterazione disponibili, vedere Lingue supportate.

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);
        }
    }
}

Dopo una chiamata riuscita, si dovrebbe vedere la risposta seguente. A differenza della chiamata all'endpoint translate, transliterate restituisce solo lo text e l'output script.

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

      "script":"latn"
   }
]

Ottenere la lunghezza delle frasi

Con il servizio Traduttore è possibile ottenere il numero di caratteri di una frase o di una serie di frasi. La risposta viene restituita in forma di matrice, con il numero di caratteri rilevato per ogni frase. È possibile ottenere la lunghezza delle frasi con gli endpoint translate e breaksentence.

Ottenere la lunghezza delle frasi durante la traduzione

Con l'endpoint translate è possibile ottenere il numero di caratteri sia del testo di origine che dell'output della traduzione. Per restituire la lunghezza delle frasi (srcSenLen e transSenLen) occorre impostare il parametro includeSentenceLength su 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);
        }
    }
}

Dopo una chiamata riuscita, si dovrebbe vedere la risposta seguente. Oltre alla lingua di origine rilevata e alla traduzione, si ottiene il numero dei caratteri di ogni frase rilevata, sia per l'origine (srcSentLen) che per la traduzione (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
               ]
            }
         }
      ]
   }
]

Ottenere la lunghezza delle frasi senza traduzione

Il servizio Traduttore consente anche di richiedere la lunghezza delle frasi senza traduzione, tramite l'endpoint breaksentence.

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);
        }
    }
}

Dopo una chiamata riuscita, si dovrebbe vedere la risposta seguente. A differenza della chiamata all'endpoint translate, breaksentence restituisce solo il numero dei caratteri del testo di origine in una matrice denominata sentLen.

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

Ricerca nel dizionario (traduzioni alternative)

Con l'endpoint è possibile ottenere traduzioni alternative per una parola o una frase. Ad esempio, quando si traduce la parola "sole" da en a es, questo endpoint restituisce "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);
        }
    }
}

Dopo una chiamata riuscita, si dovrebbe vedere la risposta seguente. Esaminiamo più attentamente la risposta, poiché il codice JSON è più complesso di alcuni degli altri esempi di questo articolo. La matrice translations include un elenco di traduzioni. Ogni oggetto nella matrice include un punteggio di attendibilità (confidence), il testo ottimizzato per la visualizzazione da parte dell'utente finale (displayTarget), il testo normalizzato (normalizedText), la parte del discorso (posTag) e le informazioni sulla traduzione precedente (backTranslations). Per altre informazioni sulla risposta, vedere Ricerca nel dizionario.

[
   {
      "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
               }
            ]
         }
      ]
   }
]

Esempi di dizionario (traduzioni nel contesto)

Dopo aver eseguito una ricerca nel dizionario, passare il testo di origine e la traduzione all'endpoint dictionary/examples, per ottenere un elenco di esempi che mostrano entrambi i termini nel contesto di un'espressione. Basandosi sull'esempio precedente, si usano i valori normalizedText e normalizedTarget della risposta della ricerca nel dizionario come text e translation, rispettivamente. I parametri della lingua di origine (from) e della destinazione di output (to) sono obbligatori.

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);
        }
    }
}

Dopo una chiamata riuscita, si dovrebbe vedere la risposta seguente. Per altre informazioni sulla risposta, vedere Ricerca nel dizionario.

[
   {
      "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."
         }
      ]
   }
]

Risoluzione dei problemi

Codici di stato HTTP comuni

Codice di stato HTTP Descrizione Possibile motivo
200 OK La richiesta è stata completata.
400 Richiesta non valida Un parametro obbligatorio è mancante, vuoto o Null. In alternativa, il valore passato a un parametro obbligatorio o facoltativo non è valido. Un problema comune è la lunghezza eccessiva dell'intestazione.
401 Non autorizzata La richiesta non è autorizzata. Assicurarsi che la chiave di sottoscrizione o il token sia valido e si trovi nell'area corretta. Vedere ancheAutenticazione.
429 Troppe richieste È stata superata la quota o la frequenza di richieste consentite per la sottoscrizione.
502 Gateway non valido Problema di rete o lato server. Può anche indicare intestazioni non valide.

Utenti Java

Se si riscontrano problemi di connessione, il certificato TLS/SSL potrebbe essere scaduto. Per risolvere questo problema, installare il certificato DigiCertGlobalRootG2.crt nell'archivio privato.

Passaggi successivi