使用 Azure AI 翻譯工具 API

在本操作指南中,您將了解如何使用翻譯工具服務 REST API。 您將先從基本範例著手,接著再了解一些在開發期間常用的核心設定選項,包括:

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶

  • Azure AI 多服務或翻譯工具資源。 擁有 Azure 訂閱後,請在 Azure 入口網站中建立單一服務多重服務資源,以取得金鑰和端點。 在其部署後,選取 [前往資源]

  • 您可以使用免費定價層 (F0) 來試用服務,之後可升級至付費層以用於生產環境。

  • 您將需要來自資源的金鑰和端點,以將應用程式連線至翻譯工具服務。 稍後需在範例程式碼中貼上金鑰和端點。 您可以在 Azure 入口網站的 [金鑰和端點] 頁面上找到這些值:

    Screenshot: Azure portal keys and endpoint page.

重要

完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性

標頭

若要透過 REST API 呼叫翻譯工具服務,必須確定每個要求中都包含下列標頭。 別擔心,我們將在以下各節的範例程式碼中包含標頭。

頁首 Condition
Ocp-Apim-Subscription-Key 來自 Azure 入口網站的翻譯工具服務金鑰。
  • 必要
Ocp-Apim-Subscription-Region 資源建立的所在區域。
  • 使用 Azure AI 多服務或區域 (地理) 資源 (例如美國西部) 時需要
  • 選用 (使用單一服務翻譯工具資源時)。
Content-Type 承載的內容類型。 接受的值為 application/jsoncharset=UTF-8
  • 必要
Content-Length 要求本文的長度
  • 選擇性
X-ClientTraceId 用於識別唯一要求的 GUID,由用戶端產生。 若您使用名為 ClientTraceId 的查詢參數,將追蹤識別碼包含在查詢字串內,就可以省略此標頭。
  • 選擇性

設定您的應用程式

  1. 請確定您已安裝最新版的 Visual Studio IDE

    提示

    如果您尚不熟悉 Visual Studio,可以參考 Visual Studio 簡介 Learn 課程模組。

  2. 開啟 Visual Studio。

  3. 在開始頁面中,請選擇 [建立新專案]

    Screenshot: Visual Studio start window.

  4. 在 [建立新的專案] 頁面的搜尋方塊中,輸入主控台。 選擇 [主控台應用程式] 範本,然後選擇 [下一步]

    Screenshot: Visual Studio's create new project page.

  5. 在 [設定新專案] 對話方塊視窗中,於 [專案名稱] 方塊中輸入 translator_text_app取消核取 [將解決方案和專案置於相同目錄中] 核取方塊,然後選取 [下一步]。

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

  6. 在 [其他資訊] 對話視窗中,請確定已選取 [.NET 6.0 (長期支援)]取消核取 [不要使用最上層陳述式] 核取方塊,並選取 [建立]

    Screenshot: Visual Studio's additional information dialog window.

使用 NuGet 安裝 Newtonsoft.json 套件

  1. 在您的 translator_quickstart 專案上按一下滑鼠右鍵,然後選取 [管理 NuGet 套件]

    Screenshot of the NuGet package search box.

  2. 選取 [瀏覽] 索引標籤並輸入 Newtonsoft。

    Screenshot of the NuGet package install window.

  3. 從正確的套件管理員視窗選取 [安裝],以將套件新增至您的專案。

    Screenshot of the NuGet package install button.

建置您的 應用程式

注意

  • 從 .NET 6 開始,使用 console 範本的新專案會產生與舊版不同的新程式樣式。
  • 新輸出會使用最新的 C# 功能,以簡化您需要撰寫的程式碼。
  • 當您使用較新版本時,只需要撰寫 Main 方法的本文。 您不需要包含最上層陳述式、全域 Using 指示詞或隱含 Using 指示詞。
  • 如需詳細資訊,請參閱新的 C# 範本產生最上層語句
  1. 開啟 Program.cs 檔案。

  2. 刪除預先存在的程式碼,包含此行 Console.WriteLine("Hello World!")。 將範例程式碼複製貼上至應用程式 Program.cs 檔案。 針對每個範例程式碼,請務必使用來自 Azure 入口網站表格辨識器執行個體的值來更新索引鍵和端點變數。

  3. 將程式碼範例新增至所需的應用程式之後,請選擇 [formRecognizer_quickstart] 旁的綠色 [開始] 按鈕來建置和執行程式,或按 F5

Screenshot of the run program button in Visual Studio.

重要

本指南中的範例需要硬式編碼的索引鍵和端點。 切記,完成時請從程式碼中移除金鑰,且切勿公開發佈金鑰。 在生產環境中,請考慮使用安全的方式來儲存及存取您的認證。 如需詳細資訊,請參閱 Azure AI 服務安全性

翻譯文字

翻譯工具服務的核心作業是翻譯文字。 在本節中,您將建置一個採用單一來源 (from) 並提供兩個輸出 (to) 的要求。 然後,我們將探討一些可用來同時調整要求和回應的參數。

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

呼叫成功後,您應該會看見下列回應:

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

您可以檢查回應標頭中每個要求的使用 (被收費的字元數):x-metered-usage 欄位。

偵測語言

若您需要翻譯,但無法得知文字的語言,可以使用語言偵測作業。 有多種方式可以識別來源文字語言。 在本節中,您將了解如何使用 translate 端點和 detect 端點進行語言偵測。

在翻譯期間偵測來源語言

如果翻譯要求中未包含 from 參數,翻譯工具服務會嘗試偵測來源文字的語言。 在回應中,您會得到偵測到的語言 (language) 和信賴度分數 (score)。 score 越接近 1.0 則偵測正確性的信賴度會越高。

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

呼叫成功後,您應該會看見下列回應:

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

偵測來源語言而不進行翻譯

您可以使用翻譯工具服務,在不進行翻譯的情況下偵測來源文字的語言。 若要這麼做,請使用 /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);
        }
    }
}

/detect 端點回應會包含替代偵測,且會指示所有偵測到的語言是否支援翻譯和音譯。 呼叫成功後,您應該會看見下列回應:

[
   {
      "language":"de",

      "score":1.0,

      "isTranslationSupported":true,

      "isTransliterationSupported":false
   }
]

音譯文字

音譯是指根據語音相似性,將一種單字或片語從一種語言的文字 (字母) 轉換為另一種語言的程序。 例如,您可以使用音譯,將 "สวัสดี" (thai) 轉換為 "sawatdi" (latn)。 有多種方式可以執行音譯。 在本節中,您將了解如何使用 translate 端點和 transliterate 端點進行語言偵測。

在翻譯期間進行音譯

如果要翻譯的目標語言使用與來源不同的字母 (或音素),就可能需進行音譯。 在此範例中,我們會將 "Hello" 從英文翻譯為泰文。 除了取得泰文翻譯外,您也將使用拉丁字母取得翻譯片語的音譯。

若要從 translate 端點取得音譯,請使用 toScript 參數。

注意

如需可用語言和音譯選項的完整清單,請參閱語言支援

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

呼叫成功後,您應該會看見下列回應。 切記,translate 端點的回應會包含偵測到的來源語言以及信賴分數、使用輸出語言字母的翻譯,以及使用拉丁字母的音譯。

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

進行音譯而不翻譯

您也可以使用 transliterate 端點來取得音譯。 使用音譯端點時,您必須提供來源語言 (language)、來源文字/字母 (fromScript) 以及輸出文字/字母 (toScript) 作為參數。 在此範例中需要取得「สวัสดีเพื่อน! วันนี้คุณทำอะไร」的音譯!

注意

如需可用語言和音譯選項的完整清單,請參閱語言支援

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

呼叫成功後,您應該會看見下列回應。 不同於呼叫 translate 端點, transliterate 只會傳回 text 和輸出 script

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

      "script":"latn"
   }
]

取得句子長度

透過翻譯工具服務,您可以取得單一句子或一系列句子的字元計數。 回應會以陣列的形式傳回,且每個偵測到的句子都會附有字元計數。 您可以使用 translatebreaksentence 端點來取得句子長度。

在翻譯期間取得句子長度

您可以使用 translate 端點,取得來源文字和翻譯輸出的字元計數。 若要傳回句子長度 (srcSenLentransSenLen),您必須將 includeSentenceLength 參數設定為 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);
        }
    }
}

呼叫成功後,您應該會看見下列回應。 除了偵測到的來源語言和翻譯以外,偵測到的每個句子也都會附有來源 (srcSentLen) 和翻譯 (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
               ]
            }
         }
      ]
   }
]

取得句子長度而不進行轉譯

翻譯工具服務也可讓您使用 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);
        }
    }
}

呼叫成功後,您應該會看見下列回應。 不同於呼叫 translate 端點, breaksentence 只會在名為 sentLen 的陣列中傳回來源文字的字元計數。

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

字典查閱 (替代翻譯)

透過端點,您可以取得單字或片語的替代翻譯。 例如,當將「work」這個字從 en 翻譯為 es 時,這個端點會傳回「luz solar」、「rayos solares」、「soleamiento」、「sol」、「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);
        }
    }
}

呼叫成功後,您應該會看見下列回應。 接下來會更仔細地檢查回應,因為 JSON 比本文中的某些其他範例更為複雜。 translations 陣列包含翻譯的清單。 此陣列中的每個物件都包含信賴分數 (confidence)、針對使用者顯示進行最佳化的文字 (displayTarget)、標準化文字 (normalizedText)、語音的部分 (posTag),以及先前翻譯的相關資訊 (backTranslations)。 如需回應的詳細資訊,請參閱字典查閱

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

字典範例 (上下文的翻譯)

執行字典查閱之後,請將來源和翻譯文字傳遞至 dictionary/examples 端點,以取得在句子或片語的上下文中顯示雙方字詞的範例清單。 以先前的範例為基礎,您將分別使用字典查閱回應中的 normalizedTextnormalizedTarget 作為 texttranslation。 您需要來源語言 (from) 和輸出目標 (to) 參數。

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

呼叫成功後,您應該會看見下列回應。 如需回應的詳細資訊,請參閱字典查閱

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

疑難排解

常見的 HTTP 狀態碼

HTTP 狀態碼 描述 可能的原因
200 確定 要求成功。
400 不正確的要求 必要的參數遺失、為空白或 Null。 或者,傳遞至必要或選用參數的值無效。 常見的問題是標頭太長。
401 未經授權 要求未獲授權。 請檢查以確定您的金鑰或權杖有效,並且位於正確的區域。 另請參閱驗證
429 過多要求 您已超出訂用帳戶允許的配額或要求率。
502 錯誤的閘道 網路或伺服器端問題。 也可能表示標頭無效。

Java 使用者

如果遇到連線問題,可能是您的 TLS/SSL 憑證已過期。 若要解決此問題,請將 DigiCertGlobalRootG2.crt 安裝到您的私人存放區。

下一步