添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
  • Azure 訂用帳戶 - 建立免費帳戶

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

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

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

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

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

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

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

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

  • 在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為您的應用程式建立一個名為 translator-text-app 的新目錄,並瀏覽至該目錄。

  • translator-text-app 目錄建立名為 text-translator.go 的新 GO 檔案。

  • 將範例程式碼複製貼上至 text-translator.go 檔案。 請務必使用來自 Azure 入口網站翻譯工具執行個體來更新索引鍵變數。

  • 將程式代碼範例新增至應用程式之後,就可以在命令或終端機提示字元中執行程式 Go 。 請確定提示路徑已設定為 translator-text-app 資料夾並使用下列命令:

     go run translation.go
    
  • Visual Studio Code 為 Windows 和 macOS 提供 Java 編碼套件。編碼套件是 VS Code、JAVA 開發套件 (JDK) 以及 Microsoft 建議延伸模組的集合。 編碼套件也可以用於修正現有的開發環境。
  • 如果您使用 VS Code 和適用於 Java 的編碼套件,請安裝 適用於 Java 的 Gradle 擴充功能。
  • 如果您未使用 Visual Studio Code,請確保在開發環境中安裝下列項目:

    Java 開發套件 (OpenJDK) 8 版或更新版本。

    Gradle,6.8 版或後續版本。

    建立新的 Gradle 專案

  • 在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為您的應用程式建立一個名為 translator-text-app 的新目錄,並瀏覽至該目錄。

    mkdir translator-text-app && translator-text-app
    
     mkdir translator-text-app; cd translator-text-app
    
  • 從 translator-text-app 目錄執行 gradle init 命令。 此命令會建立 Gradle 的基本組建檔案,包括 build.gradle.kts,將在執行階段使用 build.gradle.kts,來建立及設定應用程式。

    gradle init --type basic
    
  • 出現選擇 DSL 的提示時,請選取 [Kotlin]

  • 請選取 [退回] 或 [輸入] 以接受 translator-text-app 的預設專案名稱。

    建立整個應用程式可能需要幾分鐘的時間,但很快您應該會看到數個資料夾和檔案,包括 build-gradle.kts

  • 以下列程式碼來更新 build.gradle.kts
  • plugins {
      application
    application {
      mainClass.set("TextTranslator")
    repositories {
      mavenCentral()
    dependencies {
      implementation("com.squareup.okhttp3:okhttp:4.10.0")
      implementation("com.google.code.gson:gson:2.9.0")
    

    建立 Java 應用程式

  • 從 translator-text-app 目錄執行下列命令:

    mkdir -p src/main/java
    

    您會建立下列目錄結構:

    更新索引鍵時,請務必使用來自 Azure 入口網站翻譯工具執行個體其中一個索引鍵值。

  • 將範例程式碼新增至應用程式後,請瀏覽回您的主要專案目錄:translator-text-app,開啟主控台視窗並輸入下列命令:

  • 使用 build 命令組建您的應用程式:

    gradle build
    
  • 使用 run 命令執行您的應用程式:

    gradle run
    
  • 在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為您的應用程式建立名為 translator-text-app 的新目錄,並瀏覽至該目錄。

        mkdir translator-text-app && cd translator-text-app
    
      mkdir translator-text-app; cd translator-text-app
    
  • 執行 npm init 命令來初始化應用程式,並建構您的專案。

       npm init
    
  • 使用終端機中顯示的提示來指定專案的屬性。

  • 名稱、版本號碼和進入點是最重要的屬性。
  • 建議為進入點名稱保留 index.js。 描述、測試命令、GitHub 存放庫、關鍵字、作者和授權資訊皆為選擇性屬性,在此專案中可以跳過。
  • 選取 [退回] 或 [輸入],以接受括弧中的建議。
  • 完成提示後,將會在 translator-text-app 目錄中建立 package.json 檔案。
  • 請開啟主控台視窗並使用 npm 安裝 axios HTTP 程式庫和 uuid 套件:

       npm install axios uuid
    
  • 在應用程式目錄中建立 index.js 檔案。

  • 您可以使用 PowerShell 建立新檔案。

  • 按住 Shift 鍵並在資料夾上以滑鼠右鍵按一下,以開啟專案目錄中的 PowerShell 視窗。

  • 輸入下列命令 New-Item index.js

  • 您也可以在 IDE 中建立名為 index.js 的新檔案,並將其儲存至 translator-text-app 目錄。

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

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

    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); func main() { key := "<YOUR-TRANSLATOR-KEY>" endpoint := "https://api.cognitive.microsofttranslator.com/" uri := endpoint + "/translate?api-version=3.0" // 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. location := "<YOUR-RESOURCE-LOCATION>" // Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse u, _ := url.Parse(uri) q := u.Query() q.Add("from", "en") q.Add("to", "it") q.Add("to", "sw") u.RawQuery = q.Encode() // Create an anonymous struct for your request body and encode it to JSON body := []struct { Text string {Text: "Hello friend! What did you do today?"}, b, _ := json.Marshal(body) // Build the HTTP POST request req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b)) if err != nil { log.Fatal(err) // Add required headers to the request req.Header.Add("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. req.Header.Add("Ocp-Apim-Subscription-Region", location) req.Header.Add("Content-Type", "application/json") // Call the Translator API res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) // Decode the JSON response var result interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatal(err) // Format and print the response to terminal prettyJSON, _ := json.MarshalIndent(result, "", " ") fmt.Printf("%s\n", prettyJSON) public class TranslatorText { private static String key = "<YOUR-TRANSLATOR-KEY>"; public String endpoint = "https://api.cognitive.microsofttranslator.com"; public String route = "/translate?api-version=3.0&from=en&to=sw&to=it"; public String url = endpoint.concat(route); // 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 String location = "<YOUR-RESOURCE-LOCATION>"; // Instantiates the OkHttpClient. OkHttpClient client = new OkHttpClient(); // This function performs a POST request. public String Post() throws IOException { MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "[{\"Text\": \"Hello, friend! What did you do today?\"}]"); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. .addHeader("Ocp-Apim-Subscription-Region", location) .addHeader("Content-type", "application/json") .build(); Response response = client.newCall(request).execute(); return response.body().string(); // This function prettifies the json response. public static String prettify(String json_text) { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(json_text); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(json); public static void main(String[] args) { try { TranslatorText translateRequest = new TranslatorText(); String response = translateRequest.Post(); System.out.println(prettify(response)); } catch (Exception e) { System.out.println(e); let key = "<your-translator-key>"; let 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. let location = "<YOUR-RESOURCE-LOCATION>"; let params = new URLSearchParams(); params.append("api-version", "3.0"); params.append("from", "en"); params.append("to", "sw"); params.append("to", "it"); axios({ baseURL: endpoint, url: '/translate', method: 'post', headers: { 'Ocp-Apim-Subscription-Key': key, // location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': uuidv4().toString() params: params, data: [{ 'text': 'Hello, friend! What did you do today?' responseType: 'json' }).then(function(response){ console.log(JSON.stringify(response.data, null, 4)); # Add your key and endpoint key = "<YOUR-TRANSLATOR-KEY>" 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. location = "<YOUR-RESOURCE-LOCATION>" path = '/translate' constructed_url = endpoint + path params = { 'api-version': '3.0', 'from': 'en', 'to': ['sw', 'it'] headers = { 'Ocp-Apim-Subscription-Key': key, # location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) # You can pass more than one object in body. body = [{ 'text': 'Hello, friend! What did you do today?' request = requests.post(constructed_url, params=params, headers=headers, json=body) response = request.json() print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))

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

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

    在翻譯期間偵測來源語言

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

    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); key := "<YOUR-TRANSLATOR-KEY>" // 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. location := "<YOUR-RESOURCE-LOCATION>" endpoint := "https://api.cognitive.microsofttranslator.com/" uri := endpoint + "/translate?api-version=3.0" // Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse u, _ := url.Parse(uri) q := u.Query() q.Add("to", "en") q.Add("to", "it") u.RawQuery = q.Encode() // Create an anonymous struct for your request body and encode it to JSON body := []struct { Text string {Text: "Halo rafiki! Ulifanya nini leo?"}, b, _ := json.Marshal(body) // Build the HTTP POST request req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b)) if err != nil { log.Fatal(err) // Add required headers to the request req.Header.Add("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. req.Header.Add("Ocp-Apim-Subscription-Region", location) req.Header.Add("Content-Type", "application/json") // Call the Translator API res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) // Decode the JSON response var result interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatal(err) // Format and print the response to terminal prettyJSON, _ := json.MarshalIndent(result, "", " ") fmt.Printf("%s\n", prettyJSON) public class TranslatorText { private static String key = "<YOUR-TRANSLATOR-KEY>"; public String endpoint = "https://api.cognitive.microsofttranslator.com"; public String route = "/translate?api-version=3.0&to=en&to=it"; public String url = endpoint.concat(route); // 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 String location = "<YOUR-RESOURCE-LOCATION>"; // Instantiates the OkHttpClient. OkHttpClient client = new OkHttpClient(); // This function performs a POST request. public String Post() throws IOException { MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "[{\"Text\": \"Halo, rafiki! Ulifanya nini leo?\"}]"); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. .addHeader("Ocp-Apim-Subscription-Region", location) .addHeader("Content-type", "application/json") .build(); Response response = client.newCall(request).execute(); return response.body().string(); // This function prettifies the json response. public static String prettify(String json_text) { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(json_text); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(json); public static void main(String[] args) { try { TranslatorText translateRequest = new TranslatorText(); String response = translateRequest.Post(); System.out.println(prettify(response)); } catch (Exception e) { System.out.println(e); let key = "<YOUR-TRANSLATOR-KEY>"; let endpoint = "https://api.cognitive.microsofttranslator.com"; // Add your location, also known as region. The default is global. // This is required if using an Azure AI multi-service resource. let location = "<YOUR-RESOURCE-LOCATION>"; let params = new URLSearchParams(); params.append("api-version", "3.0"); params.append("to", "en"); params.append("to", "it"); axios({ baseURL: endpoint, url: '/translate', method: 'post', headers: { 'Ocp-Apim-Subscription-Key': key, // location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': uuidv4().toString() params: params, data: [{ 'text': 'Halo, rafiki! Ulifanya nini leo?' responseType: 'json' }).then(function(response){ console.log(JSON.stringify(response.data, null, 4)); # Add your key and endpoint key = "<YOUR-TRANSLATOR-KEY>" 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. location = "<YOUR-RESOURCE-LOCATION>" path = '/translate' constructed_url = endpoint + path params = { 'api-version': '3.0', 'to': ['en', 'it'] headers = { 'Ocp-Apim-Subscription-Key': key, # location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) # You can pass more than one object in body. body = [{ 'text': 'Halo, rafiki! Ulifanya nini leo?' request = requests.post(constructed_url, params=params, headers=headers, json=body) response = request.json() print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': '))) 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); key := "<YOUR-TRANSLATOR-KEY>" // 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. location := "<YOUR-RESOURCE-LOCATION>" endpoint := "https://api.cognitive.microsofttranslator.com/" uri := endpoint + "/detect?api-version=3.0" // Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse u, _ := url.Parse(uri) q := u.Query() u.RawQuery = q.Encode() // Create an anonymous struct for your request body and encode it to JSON body := []struct { Text string {Text: "Ciao amico! Cosa hai fatto oggi?"}, b, _ := json.Marshal(body) // Build the HTTP POST request req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b)) if err != nil { log.Fatal(err) // Add required headers to the request req.Header.Add("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. req.Header.Add("Ocp-Apim-Subscription-Region", location) req.Header.Add("Content-Type", "application/json") // Call the Translator API res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) // Decode the JSON response var result interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatal(err) // Format and print the response to terminal prettyJSON, _ := json.MarshalIndent(result, "", " ") fmt.Printf("%s\n", prettyJSON) public class TranslatorText { private static String key = "<YOUR-TRANSLATOR-KEY>"; public String endpoint = "https://api.cognitive.microsofttranslator.com"; public String route = "/detect?api-version=3.0"; public String url = endpoint.concat(route); // 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 String location = "<YOUR-RESOURCE-LOCATION>"; // Instantiates the OkHttpClient. OkHttpClient client = new OkHttpClient(); // This function performs a POST request. public String Post() throws IOException { MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "[{\"Text\": \"Hallo Freund! Was hast du heute gemacht?\"}]"); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. .addHeader("Ocp-Apim-Subscription-Region", location) .addHeader("Content-type", "application/json") .build(); Response response = client.newCall(request).execute(); return response.body().string(); // This function prettifies the json response. public static String prettify(String json_text) { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(json_text); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(json); public static void main(String[] args) { try { TranslatorText detectRequest = new TranslatorText(); String response = detectRequest.Post(); System.out.println(prettify(response)); } catch (Exception e) { System.out.println(e); let key = "<YOUR-TRANSLATOR-KEY>"; let endpoint = "https://api.cognitive.microsofttranslator.com"; // Add your location, also known as region. The default is global. // This is required if using an Azure AI multi-service resource. let location = "<YOUR-RESOURCE-LOCATION>"; let params = new URLSearchParams(); params.append("api-version", "3.0"); axios({ baseURL: endpoint, url: '/detect', method: 'post', headers: { 'Ocp-Apim-Subscription-Key': key, // location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': uuidv4().toString() params: params, data: [{ 'text': 'Hallo Freund! Was hast du heute gemacht?' responseType: 'json' }).then(function(response){ console.log(JSON.stringify(response.data, null, 4)); # Add your key and endpoint key = "<YOUR-TRANSLATOR-KEY>" 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. location = "<YOUR-RESOURCE-LOCATION>" path = '/detect' constructed_url = endpoint + path params = { 'api-version': '3.0' headers = { 'Ocp-Apim-Subscription-Key': key, # location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) # You can pass more than one object in body. body = [{ 'text': 'Hallo Freund! Was hast du heute gemacht?' request = requests.post(constructed_url, params=params, headers=headers, json=body) response = request.json() print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))

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

    在翻譯期間進行音譯

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

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

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

    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); key := "<YOUR-TRANSLATOR-KEY>" // 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. location := "<YOUR-RESOURCE-LOCATION>" endpoint := "https://api.cognitive.microsofttranslator.com/" uri := endpoint + "/translate?api-version=3.0" // Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse u, _ := url.Parse(uri) q := u.Query() q.Add("to", "th") q.Add("toScript", "latn") u.RawQuery = q.Encode() // Create an anonymous struct for your request body and encode it to JSON body := []struct { Text string {Text: "Hello, friend! What did you do today?"}, b, _ := json.Marshal(body) // Build the HTTP POST request req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b)) if err != nil { log.Fatal(err) // Add required headers to the request req.Header.Add("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. req.Header.Add("Ocp-Apim-Subscription-Region", location) req.Header.Add("Content-Type", "application/json") // Call the Translator API res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) // Decode the JSON response var result interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatal(err) // Format and print the response to terminal prettyJSON, _ := json.MarshalIndent(result, "", " ") fmt.Printf("%s\n", prettyJSON) public class TranslatorText { private static String key = "<YOUR-TRANSLATOR-KEY>"; public String endpoint = "https://api.cognitive.microsofttranslator.com"; public String route = "/translate?api-version=3.0&to=th&toScript=latn"; public String url = endpoint.concat(route); // 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 String location = "<YOUR-RESOURCE-LOCATION>"; // Instantiates the OkHttpClient. OkHttpClient client = new OkHttpClient(); // This function performs a POST request. public String Post() throws IOException { MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "[{\"Text\": \"Hello, friend! What did you do today?\"}]"); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. .addHeader("Ocp-Apim-Subscription-Region", location) .addHeader("Content-type", "application/json") .build(); Response response = client.newCall(request).execute(); return response.body().string(); // This function prettifies the json response. public static String prettify(String json_text) { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(json_text); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(json); public static void main(String[] args) { try { TranslatorText translateRequest = new TranslatorText(); String response = translateRequest.Post(); System.out.println(prettify(response)); } catch (Exception e) { System.out.println(e); let key = "<YOUR-TRANSLATOR-KEY>"; let endpoint = "https://api.cognitive.microsofttranslator.com"; // Add your location, also known as region. The default is global. // This is required if using an Azure AI multi-service resource. let location = "<YOUR-RESOURCE-LOCATION>"; let params = new URLSearchParams(); params.append("api-version", "3.0"); params.append("to", "th"); params.append("toScript", "latn"); axios({ baseURL: endpoint, url: '/translate', method: 'post', headers: { 'Ocp-Apim-Subscription-Key': key, // location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': uuidv4().toString() params: params, data: [{ 'text': 'Hello, friend! What did you do today?' responseType: 'json' }).then(function(response){ console.log(JSON.stringify(response.data, null, 4)); # Add your key and endpoint key = "<YOUR-TRANSLATOR-KEY>" 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. location = "<YOUR-RESOURCE-LOCATION>" path = '/translate' constructed_url = endpoint + path params = { 'api-version': '3.0', 'to': 'th', 'toScript': 'latn' headers = { 'Ocp-Apim-Subscription-Key': key, # location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) # You can pass more than one object in body. body = [{ 'text': 'Hello, friend! What did you do today?' request = requests.post(constructed_url, params=params, headers=headers, json=body) response = request.json() print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))

    進行音譯而不翻譯

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

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

    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); key := "<YOUR-TRANSLATOR-KEY>" // 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. location := "<YOUR-RESOURCE-LOCATION>" endpoint := "https://api.cognitive.microsofttranslator.com/" uri := endpoint + "/transliterate?api-version=3.0" // Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse u, _ := url.Parse(uri) q := u.Query() q.Add("language", "th") q.Add("fromScript", "thai") q.Add("toScript", "latn") u.RawQuery = q.Encode() // Create an anonymous struct for your request body and encode it to JSON body := []struct { Text string {Text: "สวัสดีเพื่อน! วันนี้คุณทำอะไร"}, b, _ := json.Marshal(body) // Build the HTTP POST request req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b)) if err != nil { log.Fatal(err) // Add required headers to the request req.Header.Add("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. req.Header.Add("Ocp-Apim-Subscription-Region", location) req.Header.Add("Content-Type", "application/json") // Call the Translator API res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) // Decode the JSON response var result interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatal(err) // Format and print the response to terminal prettyJSON, _ := json.MarshalIndent(result, "", " ") fmt.Printf("%s\n", prettyJSON) public class TranslatorText { private static String key = "<YOUR-TRANSLATOR-KEY>"; public String endpoint = "https://api.cognitive.microsofttranslator.com"; public String route = "/transliterate?api-version=3.0&language=th&fromScript=thai&toScript=latn"; public String url = endpoint.concat(route); // 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 String location = "<YOUR-RESOURCE-LOCATION>"; // Instantiates the OkHttpClient. OkHttpClient client = new OkHttpClient(); // This function performs a POST request. public String Post() throws IOException { MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "[{\"Text\": \"สวัสดีเพื่อน! วันนี้คุณทำอะไร\"}]"); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. .addHeader("Ocp-Apim-Subscription-Region", location) .addHeader("Content-type", "application/json") .build(); Response response = client.newCall(request).execute(); return response.body().string(); // This function prettifies the json response. public static String prettify(String json_text) { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(json_text); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(json); public static void main(String[] args) { try { TranslatorText transliterateRequest = new TranslatorText(); String response = transliterateRequest.Post(); System.out.println(prettify(response)); } catch (Exception e) { System.out.println(e); let key = "<YOUR-TRANSLATOR-KEY>"; let endpoint = "https://api.cognitive.microsofttranslator.com"; // Add your location, also known as region. The default is global. // This is required if using an Azure AI multi-service resource. let location = "<YOUR-RESOURCE-LOCATION>"; let params = new URLSearchParams(); params.append("api-version", "3.0"); params.append("language", "th"); params.append("fromScript", "thai"); params.append("toScript", "latn"); axios({ baseURL: endpoint, url: '/transliterate', method: 'post', headers: { 'Ocp-Apim-Subscription-Key': key, // location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': uuidv4().toString() params: params, data: [{ 'text': 'สวัสดีเพื่อน! วันนี้คุณทำอะไร' responseType: 'json' }).then(function(response){ console.log(JSON.stringify(response.data, null, 4)); # Add your key and endpoint key = "<YOUR-TRANSLATOR-KEY>" 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. location = "<YOUR-RESOURCE-LOCATION>" path = '/transliterate' constructed_url = endpoint + path params = { 'api-version': '3.0', 'language': 'th', 'fromScript': 'thai', 'toScript': 'latn' headers = { 'Ocp-Apim-Subscription-Key': key, # location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) # You can pass more than one object in body. body = [{ 'text': 'สวัสดีเพื่อน! วันนี้คุณทำอะไร' request = requests.post(constructed_url, params=params, headers=headers, json=body) response = request.json() print(json.dumps(response, sort_keys=True, indent=4, separators=(',', ': ')))

    取得句子長度

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

    在翻譯期間取得句子長度

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

    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); key := "<YOUR-TRANSLATOR-KEY>" // 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. location := "<YOUR-RESOURCE-LOCATION>" endpoint := "https://api.cognitive.microsofttranslator.com/" uri := endpoint + "/translate?api-version=3.0" // Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse u, _ := url.Parse(uri) q := u.Query() q.Add("to", "es") q.Add("includeSentenceLength", "true") u.RawQuery = q.Encode() // Create an anonymous struct for your request body and encode it to JSON body := []struct { Text string {Text: "Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine."}, b, _ := json.Marshal(body) // Build the HTTP POST request req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b)) if err != nil { log.Fatal(err) // Add required headers to the request req.Header.Add("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. req.Header.Add("Ocp-Apim-Subscription-Region", location) req.Header.Add("Content-Type", "application/json") // Call the Translator API res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) // Decode the JSON response var result interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatal(err) // Format and print the response to terminal prettyJSON, _ := json.MarshalIndent(result, "", " ") fmt.Printf("%s\n", prettyJSON) public class TranslatorText { private static String key = "<YOUR-TRANSLATOR-KEY>"; public String endpoint = "https://api.cognitive.microsofttranslator.com"; public String route = "/translate?api-version=3.0&to=es&includeSentenceLength=true"; public static String url = endpoint.concat(route); // 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 String location = "<YOUR-RESOURCE-LOCATION>"; // Instantiates the OkHttpClient. OkHttpClient client = new OkHttpClient(); // This function performs a POST request. public String Post() throws IOException { MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "[{\"Text\": \"Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.\"}]"); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. .addHeader("Ocp-Apim-Subscription-Region", location) .addHeader("Content-type", "application/json") .build(); Response response = client.newCall(request).execute(); return response.body().string(); // This function prettifies the json response. public static String prettify(String json_text) { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(json_text); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(json); public static void main(String[] args) { try { TranslatorText translateRequest = new TranslatorText(); String response = translateRequest.Post(); System.out.println(prettify(response)); } catch (Exception e) { System.out.println(e); let key = "<YOUR-TRANSLATOR-KEY>"; let endpoint = "https://api.cognitive.microsofttranslator.com"; // Add your location, also known as region. The default is global. // This is required if using an Azure AI multi-service resource. let location = "<YOUR-RESOURCE-LOCATION>"; let params = new URLSearchParams(); params.append("api-version", "3.0"); params.append("to", "es"); params.append("includeSentenceLength", true); axios({ baseURL: endpoint, url: '/translate', method: 'post', headers: { 'Ocp-Apim-Subscription-Key': key, // location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': uuidv4().toString() params: params, data: [{ 'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.' responseType: 'json' }).then(function(response){ console.log(JSON.stringify(response.data, null, 4)); # Add your key and endpoint key = "<YOUR-TRANSLATOR-KEY>" 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. location = "<YOUR-RESOURCE-LOCATION>" path = '/translate' constructed_url = endpoint + path params = { 'api-version': '3.0', 'to': 'es', 'includeSentenceLength': True headers = { 'Ocp-Apim-Subscription-Key': key, # location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) # You can pass more than one object in body. body = [{ 'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.' request = requests.post(constructed_url, params=params, headers=headers, json=body) response = request.json() print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))

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

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

    翻譯工具服務也可讓您使用 breaksentence 端點,在不進行轉譯的情況下要求句子長度。

    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); key := "<YOUR-TRANSLATOR-KEY>" // 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. location := "<YOUR-RESOURCE-LOCATION>" endpoint := "https://api.cognitive.microsofttranslator.com/" uri := endpoint + "/breaksentence?api-version=3.0" // Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse u, _ := url.Parse(uri) q := u.Query() u.RawQuery = q.Encode() // Create an anonymous struct for your request body and encode it to JSON body := []struct { Text string {Text: "Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine."}, b, _ := json.Marshal(body) // Build the HTTP POST request req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b)) if err != nil { log.Fatal(err) // Add required headers to the request req.Header.Add("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. req.Header.Add("Ocp-Apim-Subscription-Region", location) req.Header.Add("Content-Type", "application/json") // Call the Translator API res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) // Decode the JSON response var result interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatal(err) // Format and print the response to terminal prettyJSON, _ := json.MarshalIndent(result, "", " ") fmt.Printf("%s\n", prettyJSON) public class TranslatorText { private static String key = "<YOUR-TRANSLATOR-KEY>"; public String endpoint = "https://api.cognitive.microsofttranslator.com"; public String route = "/breaksentence?api-version=3.0"; public String url = endpoint.concat(route); // 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 String location = "<YOUR-RESOURCE-LOCATION>"; // Instantiates the OkHttpClient. OkHttpClient client = new OkHttpClient(); // This function performs a POST request. public String Post() throws IOException { MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "[{\"Text\": \"Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.\"}]"); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. .addHeader("Ocp-Apim-Subscription-Region", location) .addHeader("Content-type", "application/json") .build(); Response response = client.newCall(request).execute(); return response.body().string(); // This function prettifies the json response. public static String prettify(String json_text) { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(json_text); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(json); public static void main(String[] args) { try { TranslatorText breakSentenceRequest = new TranslatorText(); String response = breakSentenceRequest.Post(); System.out.println(prettify(response)); } catch (Exception e) { System.out.println(e); let key = "<YOUR-TRANSLATOR-KEY>"; let endpoint = "https://api.cognitive.microsofttranslator.com"; // Add your location, also known as region. The default is global. // This is required if using an Azure AI multi-service resource. let location = "<YOUR-RESOURCE-LOCATION>"; let params = new URLSearchParams(); params.append("api-version", "3.0"); axios({ baseURL: endpoint, url: '/breaksentence', method: 'post', headers: { 'Ocp-Apim-Subscription-Key': key, // location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': uuidv4().toString() params: params, data: [{ 'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.' responseType: 'json' }).then(function(response){ console.log(JSON.stringify(response.data, null, 4)); # Add your key and endpoint key = "<YOUR-TRANSLATOR-KEY>" 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. location = "<YOUR-RESOURCE-LOCATION>" path = '/breaksentence' constructed_url = endpoint + path params = { 'api-version': '3.0' headers = { 'Ocp-Apim-Subscription-Key': key, # location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) # You can pass more than one object in body. body = [{ 'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.' request = requests.post(constructed_url, params=params, headers=headers, json=body) response = request.json() print(json.dumps(response, sort_keys=True, indent=4, separators=(',', ': '))) 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); key := "<YOUR-TRANSLATOR-KEY>" // 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. location := "<YOUR-RESOURCE-LOCATION>" endpoint := "https://api.cognitive.microsofttranslator.com/" uri := endpoint + "/dictionary/lookup?api-version=3.0" // Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse u, _ := url.Parse(uri) q := u.Query() q.Add("from", "en") q.Add("to", "es") u.RawQuery = q.Encode() // Create an anonymous struct for your request body and encode it to JSON body := []struct { Text string {Text: "sunlight"}, b, _ := json.Marshal(body) // Build the HTTP POST request req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b)) if err != nil { log.Fatal(err) // Add required headers to the request req.Header.Add("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. req.Header.Add("Ocp-Apim-Subscription-Region", location) req.Header.Add("Content-Type", "application/json") // Call the Translator API res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) // Decode the JSON response var result interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatal(err) // Format and print the response to terminal prettyJSON, _ := json.MarshalIndent(result, "", " ") fmt.Printf("%s\n", prettyJSON) public class TranslatorText { private static String key = "<YOUR-TRANSLATOR-KEY>"; public String endpoint = "https://api.cognitive.microsofttranslator.com"; public String route = "/dictionary/lookup?api-version=3.0&from=en&to=es"; public String url = endpoint.concat(route); // 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 String location = "<YOUR-RESOURCE-LOCATION>"; // Instantiates the OkHttpClient. OkHttpClient client = new OkHttpClient(); // This function performs a POST request. public String Post() throws IOException { MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "[{\"Text\": \"sunlight\"}]"); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. .addHeader("Ocp-Apim-Subscription-Region", location) .addHeader("Content-type", "application/json") .build(); Response response = client.newCall(request).execute(); return response.body().string(); // This function prettifies the json response. public static String prettify(String json_text) { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(json_text); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(json); public static void main(String[] args) { try { TranslatorText breakSentenceRequest = new TranslatorText(); String response = breakSentenceRequest.Post(); System.out.println(prettify(response)); } catch (Exception e) { System.out.println(e); let key = "<YOUR-TRANSLATOR-KEY>"; let endpoint = "https://api.cognitive.microsofttranslator.com"; // Add your location, also known as region. The default is global. // This is required if using an Azure AI multi-service resource. let location = "<YOUR-RESOURCE-LOCATION>"; let params = new URLSearchParams(); params.append("api-version", "3.0"); params.append("from", "en"); params.append("to", "es"); axios({ baseURL: endpoint, url: '/dictionary/lookup', method: 'post', headers: { 'Ocp-Apim-Subscription-Key': key, // location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': uuidv4().toString() params: params, data: [{ 'text': 'sunlight' responseType: 'json' }).then(function(response){ console.log(JSON.stringify(response.data, null, 4)); # Add your key and endpoint key = "<YOUR-TRANSLATOR-KEY>" 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. location = "<YOUR-RESOURCE-LOCATION>" path = '/dictionary/lookup' constructed_url = endpoint + path params = { 'api-version': '3.0', 'from': 'en', 'to': 'es' headers = { 'Ocp-Apim-Subscription-Key': key, # location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) # You can pass more than one object in body. body = [{ 'text': 'sunlight' request = requests.post(constructed_url, params=params, headers=headers, json=body) response = request.json() print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))

    呼叫成功後,您應該會看見下列回應。 接下來會更仔細地檢查回應,因為 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) 參數。

    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); key := "<YOUR-TRANSLATOR-KEY>" // 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. location := "<YOUR-RESOURCE-LOCATION>" endpoint := "https://api.cognitive.microsofttranslator.com/" uri := endpoint + "/dictionary/examples?api-version=3.0" // Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse u, _ := url.Parse(uri) q := u.Query() q.Add("from", "en") q.Add("to", "es") u.RawQuery = q.Encode() // Create an anonymous struct for your request body and encode it to JSON body := []struct { Text string Translation string Text: "sunlight", Translation: "luz solar", b, _ := json.Marshal(body) // Build the HTTP POST request req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b)) if err != nil { log.Fatal(err) // Add required headers to the request req.Header.Add("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. req.Header.Add("Ocp-Apim-Subscription-Region", location) req.Header.Add("Content-Type", "application/json") // Call the Translator Text API res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) // Decode the JSON response var result interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatal(err) // Format and print the response to terminal prettyJSON, _ := json.MarshalIndent(result, "", " ") fmt.Printf("%s\n", prettyJSON) public class TranslatorText { private static String key = "<YOUR-TRANSLATOR-KEY>"; public String endpoint = "https://api.cognitive.microsofttranslator.com"; public String route = "/dictionary/examples?api-version=3.0&from=en&to=es"; public String url = endpoint.concat(route); // 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 String location = "<YOUR-RESOURCE-LOCATION>"; // Instantiates the OkHttpClient. OkHttpClient client = new OkHttpClient(); // This function performs a POST request. public String Post() throws IOException { MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "[{\"Text\": \"sunlight\", \"Translation\": \"luz solar\"}]"); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. .addHeader("Ocp-Apim-Subscription-Region", location) .addHeader("Content-type", "application/json") .build(); Response response = client.newCall(request).execute(); return response.body().string(); // This function prettifies the json response. public static String prettify(String json_text) { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(json_text); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(json); public static void main(String[] args) { try { TranslatorText dictionaryExamplesRequest = new TranslatorText(); String response = dictionaryExamplesRequest.Post(); System.out.println(prettify(response)); } catch (Exception e) { System.out.println(e); let key = "<YOUR-TRANSLATOR-KEY>"; let endpoint = "https://api.cognitive.microsofttranslator.com"; // Add your location, also known as region. The default is global. // This is required if using an Azure AI multi-service resource. let location = "<YOUR-RESOURCE-LOCATION>"; let params = new URLSearchParams(); params.append("api-version", "3.0"); params.append("from", "en"); params.append("to", "es"); axios({ baseURL: endpoint, url: '/dictionary/examples', method: 'post', headers: { 'Ocp-Apim-Subscription-Key': key, // location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': uuidv4().toString() params: params, data: [{ 'text': 'sunlight', 'translation': 'luz solar' responseType: 'json' }).then(function(response){ console.log(JSON.stringify(response.data, null, 4)); # Add your key and endpoint key = "<YOUR-TRANSLATOR-KEY>" 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. location = "<YOUR-RESOURCE-LOCATION>" path = '/dictionary/examples' constructed_url = endpoint + path params = { 'api-version': '3.0', 'from': 'en', 'to': 'es' headers = { 'Ocp-Apim-Subscription-Key': key, # location required if you're using a multi-service or regional (not global) resource. 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) # You can pass more than one object in body. body = [{ 'text': 'sunlight', 'translation': 'luz solar' request = requests.post(constructed_url, params=params, headers=headers, json=body) response = request.json() print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': '))) "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 狀態代碼 可能的原因

    Java 使用者

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

    自訂及改善翻譯

  •