Azure AI Translator API を使用する

この攻略ガイドでは、Translator サービス REST API の使用方法について説明します。 基本的な例から始めて、開発時によく使用される、次のような主要な構成オプションに進みます。

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します

  • Azure AI マルチサービスまたは Translator リソース。 Azure サブスクリプションを用意できたら、Azure portal で単一サービスまたはマルチサービスのリソースを作成し、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] を選択します。

  • Free 価格レベル (F0) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。

  • 自分のアプリケーションを Translator サービスに接続するには、リソースのキーとエンドポイントが必要です。 後で、コード サンプルに自分のキーとエンドポイントを貼り付けます。 これらの値は Azure portal の [キーとエンドポイント] ページで確認できます。

    スクリーンショット: Azure portal の [キーとエンドポイント] ページ。

重要

終わったらコードからキーを削除し、公開しないよう注意してください。 運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 詳細については、「Azure AI サービスのセキュリティ」を "参照" してください。

ヘッダー

REST API を使用して Translator サービスを呼び出すには、次のヘッダーを各要求に含める必要があります。 ご安心ください。以降の各セクションのサンプル コードにはヘッダーが含まれています。

ヘッダー 条件
Ocp-Apim-Subscription-Key Azure portal からの Translator サービス キー。
  • 必須
Ocp-Apim-Subscription-Region リソースが作成されたリージョン。
  • Azure AI マルチサービスまたはリージョン (地理的) リソース (米国西部など) を使用する場合は "必須"。
  • 単一サービス Translator リソースを使用する場合は、"省略可能"。
Content-Type ペイロードのコンテンツ タイプ。 許容される値は application/json または charset=UTF-8 です。
  • 必須
Content-Length 要求本文の長さ
  • オプション
X-ClientTraceId 要求を一意に識別する、クライアントで生成された GUID。 ClientTraceId という名前のクエリ パラメーターを使用してクエリ文字列内にトレース ID を含める場合、このヘッダーは省略できます。
  • オプション

アプリケーションの設定

  1. 現在のバージョンの Visual Studio IDE があることを確認します。

    ヒント

    Visual Studio を初めて使う場合は、「Visual Studio の概要」Learn モジュールを試してください。

  2. Visual Studio を開きます。

  3. スタート ページで、[新しいプロジェクトの作成] を選択します。

    スクリーンショット: Visual Studio のスタート ウィンドウ。

  4. [新しいプロジェクトの作成] ページで、検索ボックスに「コンソール」と入力します。 [コンソール アプリケーション] テンプレートを選択し、 [次へ] を選択します。

    スクリーンショット: Visual Studio の [新しいプロジェクトの作成] ページ。

  5. [新しいプロジェクトの構成] ダイアログ ウィンドウの [プロジェクト名] ボックスに「translator_text_app」と入力します。 [ソリューションとプロジェクトを同じディレクトリに配置する] チェック ボックスをオフのままにして、[次へ] を選択します。

    スクリーンショット: Visual Studio の [新しいプロジェクトの構成] ダイアログ ウィンドウ。

  6. [追加情報] ダイアログ ウィンドウで、[.NET 6.0 (長期的なサポート)] が選択されていることを確認します。 [最上位レベルのステートメントを使用しない] チェック ボックスをオフのままにし、[作成] を選択します。

    スクリーンショット: Visual Studio の [追加情報] ダイアログ ウィンドウ。

NuGet を使用して Newtonsoft.json パッケージをインストールする

  1. translator_quickstart プロジェクトを右クリックし、[NuGet パッケージの管理...] を選択します。

    NuGet パッケージの検索ボックスのスクリーンショット。

  2. [参照] タブを選択し、「Newtonsoft」と入力します。

    NuGet パッケージのインストール ウィンドウのスクリーンショット。

  3. 適切なパッケージ マネージャー ウィンドウから [インストール] を選択して、プロジェクトにパッケージを追加します。

    NuGet パッケージのインストール ボタンのスクリーンショット。

アプリケーションをビルドする

注意

  • .NET 6 以降では、console テンプレートを使用する新しいプロジェクトによって、以前のバージョンとは異なる新しいプログラム スタイルが生成されます。
  • この新しい出力では、記述する必要があるコードを簡素化できる最新の C# 機能が使用されています。
  • 新しいバージョンで使用する場合、記述する必要があるのは、`Main` メソッドの本体のみです。 最上位レベルのステートメント、グローバル using ディレクティブ、または暗黙的な using ディレクティブを含める必要はありません。
  • 詳細については、「新しい C# テンプレートで、最上位レベルのステートメントが生成される」を "参照" してください。
  1. Program.cs ファイルを開きます。

  2. Console.WriteLine("Hello World!") を含む既存のコードを削除します。 コード サンプルをコピーして、アプリケーションの Program.cs ファイルに貼り付けます。 各コード サンプルで、キー変数とエンドポイント変数を Azure portal の Translator インスタンスからの値で更新してください。

  3. アプリケーションに目的のコード サンプルを追加したら、[formRecognizer_quickstart] の横にある緑色の [開始] ボタンを選択してプログラムをビルドして実行するか、または F5 キーを押します。

Visual Studio のプログラム実行ボタンのスクリーンショット。

重要

このガイドのサンプルでは、ハードコーディングされたキーとエンドポイントが必要です。 終わったらコードからキーを削除し公開しないよう注意してください。 運用環境では、資格情報を安全に格納して利用するための方法を用いることを検討してください。 詳しくは、「Azure AI サービスのセキュリティ」を "ご覧" ください。

テキストを翻訳する

Translator サービスの主要な操作は、テキストの翻訳です。 このセクションでは、1 つのソース (from) を受け取り、2 つの出力 (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 パラメーターが含まれていない場合は、Translator サービスによってソース テキストの言語の検出が試行されます。 応答では、検出された言語 (language) と信頼度スコア (score) が返されます。 score1.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"
         }
      ]
   }
]

翻訳せずにソース言語を検出する

Translator サービスでは、翻訳を実行せずに、ソース テキストの言語を検出することもできます。 これを行うには、/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 パラメーターを使用します。

Note

使用できる言語と表記変換オプションの完全な一覧については、言語サポートに関するページを参照してください。

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) をパラメーターとして指定する必要があります。 この例では、สวัสดีเพื่อน の表記変換を取得します。 วันนี้คุณทำอะไร。

Note

使用できる言語と表記変換オプションの完全な一覧については、言語サポートに関するページを参照してください。

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

文の長さを取得する

Translator サービスを使用すると、一文または一連の文の文字数を取得できます。 応答は、検出された各文の文字数を含む配列として返されます。 文の長さは、translate および breaksentence エンドポイントを使用して取得できます。

翻訳中に文の長さを取得する

translate エンドポイントを使用して、ソース テキストと翻訳出力の両方の文字数を取得できます。 文の長さ (srcSenLen および transSenLen) を返すには、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
               ]
            }
         }
      ]
   }
]

翻訳せずに文の長さを取得する

また、Translator サービスでは、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
      ]
   }
]

辞書検索 (翻訳の代替候補)

エンドポイントを使用すると、単語または語句の翻訳の代替候補を取得できます。 たとえば、"sunshine" という単語を 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 OK 要求は成功しました。
400 正しくない要求 必須パラメーターが指定されていない、空、または null です。 または、必須またはオプションのパラメーターに渡された値が無効です。 よくある問題はヘッダーが長すぎることです。
401 権限がありません 要求は承認されません。 キーまたはトークンが有効であり、正しいリージョンにあることを確認してください。 認証」も参照してください。
429 要求が多すぎます 使用中のサブスクリプションで許可されている要求のクォータまたは速度を超えています。
502 無効なゲートウェイ ネットワークまたはサーバー側の問題です。 無効なヘッダーを示す場合もあります。

Java ユーザー

接続の問題が発生した場合、TLS/SSL 証明書の有効期限が切れている可能性があります。 この問題を解決するには、DigiCertGlobalRootG2.crt をプライベート ストアにインストールします。

次の手順