I den här instruktionsguiden lär du dig att använda TRANSLATOR-tjänstens REST-API:er. Du börjar med grundläggande exempel och går vidare till några grundläggande konfigurationsalternativ som ofta används under utvecklingen, inklusive:
En Azure AI-resurs för flera tjänster eller Translator-resurser. När du har din Azure-prenumeration skapar du en enskild tjänst eller en resurs med flera tjänster i Azure Portal för att hämta din nyckel och slutpunkt. När den har distribuerats väljer du Gå till resurs.
Du kan använda den kostnadsfria prisnivån (F0) för att prova tjänsten och uppgradera senare till en betald nivå för produktion.
Du behöver nyckeln och slutpunkten från resursen för att ansluta ditt program till Translator-tjänsten. Senare klistrar du in din nyckel och slutpunkt i kodexemplen. Du hittar dessa värden på sidan Azure Portal Nycklar och slutpunkt:
Viktigt!
Kom ihåg att ta bort nyckeln från koden när du är klar och publicera den aldrig offentligt. För produktion använder du ett säkert sätt att lagra och komma åt dina autentiseringsuppgifter som Azure Key Vault. Mer information finns i Säkerhet för Azure AI-tjänster.
Sidhuvuden
Om du vill anropa Translator-tjänsten via REST-API:et måste du se till att följande rubriker ingår i varje begäran. Oroa dig inte, vi inkluderar rubrikerna i exempelkoden i följande avsnitt.
Header
Värde
Villkor
Ocp-Apim-Subscription-Key
Din Translator-tjänstnyckel från Azure Portal.
Krävs
Ocp-Apim-Subscription-Region
Den region där resursen skapades.
Krävs när du använder en Azure AI-resurs för flera tjänster eller regional (geografisk) som USA, västra.
Valfritt när du använder en translatorresurs med en enda tjänst.
Innehållstyp
Nyttolastens innehållstyp. Det godkända värdet är application/json eller charset=UTF-8.
Krävs
Innehållslängd
Längden på begärandetexten .
Valfritt
X-ClientTraceId
Ett klientgenererat GUID för att unikt identifiera begäran. Du kan utelämna den här rubriken om du inkluderar spårnings-ID:t i frågesträngen med hjälp av en frågeparameter med namnet ClientTraceId.
På sidan Skapa ett nytt projekt anger du konsolen i sökrutan. Välj mallen Konsolprogram och välj sedan Nästa.
I dialogrutan Konfigurera det nya projektet anger du translator_text_app i rutan Projektnamn. Låt kryssrutan "Placera lösning och projekt i samma katalog" vara avmarkerad och välj Nästa.
I dialogrutan Ytterligare information kontrollerar du att .NET 6.0 (långsiktigt stöd) har valts. Låt kryssrutan "Använd inte toppnivåinstruktioner" vara avmarkerad och välj Skapa.
Installera Newtonsoft.json-paketet med NuGet
Högerklicka på ditt translator_quickstart projekt och välj Hantera NuGet-paket... .
Välj fliken Bläddra och skriv Newtonsoft.
Välj installera från rätt pakethanterarfönster och lägg till paketet i projektet.
Skapa ditt program
Kommentar
Från och med .NET 6 genererar nya projekt med mallen console ett nytt programformat som skiljer sig från tidigare versioner.
De nya utdata använder de senaste C#-funktionerna som förenklar koden du behöver skriva.
När du använder den nyare versionen behöver du bara skriva metodens Main brödtext. Du behöver inte inkludera toppnivåinstruktioner, globala användningsdirektiv eller implicita med hjälp av direktiv.
Ta bort den befintliga koden, inklusive raden Console.WriteLine("Hello World!"). Kopiera och klistra in kodexemplen i programmets Program.cs-fil. För varje kodexempel kontrollerar du att du uppdaterar nyckel- och slutpunktsvariablerna med värden från din Azure Portal Translator-instans.
När du har lagt till ett önskat kodexempel i programmet väljer du den gröna startknappen bredvid formRecognizer_quickstart för att skapa och köra programmet, eller tryck på F5.
Ladda ned Go-programversionen för operativsystemet.
När nedladdningen är klar kör du installationsprogrammet.
Öppna en kommandotolk och ange följande för att bekräfta att Go har installerats:
go version
I ett konsolfönster (till exempel cmd, PowerShell eller Bash) skapar du en ny katalog för din app med namnet translator-text-app och navigerar till den.
Skapa en ny GO-fil med namnet text-translator.go från katalogen translator-text-app .
Kopiera och klistra in kodexemplen i filen text-translator.go . Se till att du uppdaterar nyckelvariabeln med värdet från din Azure Portal Translator-instans.
När du har lagt till ett kodexempel i ditt program kan go-programmet köras i en kommandotolk eller terminalprompt. Kontrollera att promptens sökväg är inställd på mappen translator-text-app och använd följande kommando:
Visual Studio Code erbjuder ett kodningspaket för Java för Windows och macOS. Kodningspaketet är ett paket med VS Code, Java Development Kit (JDK) och en samling föreslagna tillägg från Microsoft. Kodningspaketet kan också användas för att åtgärda en befintlig utvecklingsmiljö.
I konsolfönstret (till exempel cmd, PowerShell eller Bash) skapar du en ny katalog för din app med namnet translator-text-app och navigerar till den.
mkdir translator-text-app && translator-text-app
mkdir translator-text-app; cd translator-text-app
gradle init Kör kommandot från katalogen translator-text-app. Det här kommandot skapar viktiga byggfiler för Gradle, inklusive build.gradle.kts, som används vid körning för att skapa och konfigurera ditt program.
gradle init --type basic
Välj en DSL när du uppmanas till det och välj Kotlin.
Acceptera standardprojektets namn (translator-text-app) genom att välja Retur eller Retur.
Kommentar
Det kan ta några minuter innan hela programmet skapas, men snart bör du se flera mappar och filer, inklusive build-gradle.kts.
Kör följande kommando från katalogen translator-text-app:
mkdir -p src/main/java
Du skapar följande katalogstruktur:
Navigera till java katalogen och skapa en fil med namnet TranslatorText.java.
Dricks
Du kan skapa en ny fil med hjälp av PowerShell.
Öppna ett PowerShell-fönster i projektkatalogen genom att hålla ned Skift-tangenten och högerklicka på mappen.
Skriv följande kommando new-item TranslatorText.java.
Du kan också skapa en ny fil i din IDE med namnet TranslatorText.java och spara den i java katalogen.
Kopiera och klistra in kodexempelfilen TranslatorText.java . Se till att du uppdaterar nyckeln med ett av nyckelvärdena från din Azure Portal Translator-instans.
När du har lagt till ett kodexempel i programmet går du tillbaka till huvudprojektkatalogen – translator-text-app, öppnar ett konsolfönster och anger följande kommandon:
Skapa ditt program med build kommandot :
gradle build
Kör programmet med run kommandot :
gradle run
Om den inte är installerad i utvecklingsmiljön laddar du ned den senaste versionen av Node.js. Node Package Manager (npm) ingår i installationen av Node.js.
I ett konsolfönster (till exempel cmd, PowerShell eller Bash) skapar och navigerar du till en ny katalog för din app med namnet translator-text-app.
mkdir translator-text-app && cd translator-text-app
mkdir translator-text-app; cd translator-text-app
Kör kommandot npm init för att initiera programmet och skapa en autogenerering av projektet.
npm init
Ange projektets attribut med hjälp av de prompter som visas i terminalen.
De viktigaste attributen är namn, versionsnummer och startpunkt.
Vi rekommenderar att du behåller index.js namnet på startpunkten. Beskrivningen, testkommandot, GitHub-lagringsplatsen, nyckelord, författare och licensinformation är valfria attribut – de kan hoppas över för det här projektet.
Acceptera förslagen inom parenteser genom att välja Retur eller Retur.
När du har slutfört anvisningarna skapas en package.json fil i katalogen translator-text-app.
Öppna ett konsolfönster och använd npm för att installera axios HTTP-biblioteket och uuid -paketet:
npm install axios uuid
index.js Skapa filen i programkatalogen.
Dricks
Du kan skapa en ny fil med hjälp av PowerShell.
Öppna ett PowerShell-fönster i projektkatalogen genom att hålla ned Skift-tangenten och högerklicka på mappen.
Skriv följande kommando new-item index.js.
Du kan också skapa en ny fil med namnet index.js i din IDE och spara den i translator-text-app katalogen.
Kopiera och klistra in kodexemplen i index.js filen. Se till att du uppdaterar nyckelvariabeln med värdet från din Azure Portal Translator-instans.
När du har lagt till kodexemplet i programmet kör du programmet:
Gå till programkatalogen (translator-text-app).
Skriv följande kommando i terminalen:
node index.js
Om du inte har den i utvecklingsmiljön installerar du den senaste versionen av Python 3.x. Python Installer-paketet (pip) ingår i Python-installationen.
Öppna ett terminalfönster och använd pip för att installera begärandebiblioteket och uuid0-paketet:
pip install requests uuid
Kommentar
Vi använder också ett inbyggt Python-paket med namnet json. Den används för att arbeta med JSON-data.
Skapa en ny Python-fil med namnet text-translator.py i önskad redigerare eller IDE.
Lägg till följande kodexempel i text-translator.py filen. Se till att du uppdaterar nyckeln med ett av värdena från din Azure Portal Translator-instans.
När du har lagt till ett önskat kodexempel i programmet skapar och kör du programmet:
Gå till din text-translator.py-fil .
Skriv följande kommando i konsolen:
python text-translator.py
Viktigt!
Exemplen i den här guiden kräver hårdkodade nycklar och slutpunkter.
Kom ihåg att ta bort nyckeln från koden när du är klar och publicera den aldrig offentligt.
För produktion bör du överväga att använda ett säkert sätt att lagra och komma åt dina autentiseringsuppgifter. Mer information finns iSäkerhet för Azure AI-tjänster.
Översätta text
Translator-tjänstens kärnåtgärd är att översätta text. I det här avsnittet skapar du en begäran som tar en enda källa (from) och tillhandahåller två utdata (to). Sedan granskar vi några parametrar som kan användas för att justera både begäran och svaret.
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
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)
}
import java.io.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
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));
})
import requests, uuid, json
# 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=(',', ': ')))
Efter ett lyckat anrop bör du se följande svar:
[
{
"translations":[
{
"text":"Halo, rafiki! Ulifanya nini leo?",
"to":"sw"
},
{
"text":"Ciao, amico! Cosa hai fatto oggi?",
"to":"it"
}
]
}
]
Om du behöver översättning, men inte känner till språket i texten, kan du använda språkidentifieringsåtgärden. Det finns mer än ett sätt att identifiera källtextspråket. I det här avsnittet får du lära dig hur du använder språkidentifiering med hjälp av translate slutpunkten och detect slutpunkten.
Identifiera källspråk under översättning
Om du inte tar med parametern from i översättningsbegäran försöker Translator-tjänsten identifiera källtextens språk. I svaret får du det identifierade språket (language) och en konfidenspoäng (score). Ju närmare score är 1.0, innebär att det finns ett ökat förtroende för att identifieringen är korrekt.
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
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)
}
import java.io.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
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));
})
import requests, uuid, json
# 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=(',', ': ')))
Efter ett lyckat anrop bör du se följande svar:
[
{
"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"
}
]
}
]
Identifiera källspråk utan översättning
Det är möjligt att använda Translator-tjänsten för att identifiera källtextens språk utan att utföra en översättning. Om du vill göra det använder /detect du slutpunkten.
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
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)
}
import java.io.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
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));
})
import requests, uuid, json
# 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=(',', ': ')))
Slutpunktssvaret /detect innehåller alternativa identifieringar och anger om översättningen och transkriberingen stöds för alla identifierade språk. Efter ett lyckat anrop bör du se följande svar:
Transkribering är processen att konvertera ett ord eller en fras från skriptet (alfabetet) för ett språk till ett annat baserat på fonetisk likhet. Du kan till exempel använda transliteration för att konvertera "สวัสดี" (thai) till "sawatdi" (latn). Det finns mer än ett sätt att utföra transliteration. I det här avsnittet får du lära dig hur du använder språkidentifiering med hjälp av translate slutpunkten och transliterate slutpunkten.
Transkribera under översättning
Om du översätter till ett språk som använder ett annat alfabet (eller fonem) än källan kan du behöva en transliteration. I det här exemplet översätter vi "Hello" från engelska till thailändska. Förutom att få översättningen på thailändska får du en transkribering av den översatta frasen med hjälp av det latinska alfabetet.
Använd parametern translatetoScript för att hämta en transliteration från slutpunkten.
Kommentar
En fullständig lista över tillgängliga språk och transkriberingsalternativ finns i språkstöd.
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
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)
}
import java.io.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
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));
})
import requests, uuid, json
# 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=(',', ': ')))
Efter ett lyckat anrop bör du se följande svar. Tänk på att svaret från translate slutpunkten innehåller det identifierade källspråket med en konfidenspoäng, en översättning med hjälp av alfabetet för utdataspråket och en transkribering med hjälp av det latinska alfabetet.
Du kan också använda transliterate slutpunkten för att hämta en transliteration. När du använder transliterationsslutpunkten måste du ange källspråket (language), källskriptet/alfabetet (fromScript) och utdataskriptet/alfabetet (toScript) som parametrar. I det här exemplet ska vi hämta transliterationen för สวัสดีเพื่อน! วันนี้คุณทำอะไร.
Kommentar
En fullständig lista över tillgängliga språk och transkriberingsalternativ finns i språkstöd.
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
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)
}
import java.io.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
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));
})
import requests, uuid, json
# 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=(',', ': ')))
Efter ett lyckat anrop bör du se följande svar. Till skillnad från anropet translate till slutpunkten transliterate returnerar text endast utdata scriptoch .
Med Translator-tjänsten kan du få teckenantalet för en mening eller en serie meningar. Svaret returneras som en matris, med teckenantal för varje mening identifierad. Du kan hämta meningslängder med slutpunkterna translate och breaksentence .
Hämta meningslängd under översättning
Du kan hämta teckenantal för både källtext och översättningsutdata med hjälp av translate slutpunkten. Om du vill returnera meningslängden (srcSenLen och transSenLen) måste du ange parametern includeSentenceLength till 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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
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)
}
import java.io.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
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));
})
import requests, uuid, json
# 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=(',', ': ')))
Efter ett lyckat anrop bör du se följande svar. Förutom det identifierade källspråket och översättningen får du teckenantal för varje identifierad mening för både källan (srcSentLen) och översättningen (transSentLen).
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
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));
})
import requests, uuid, json
# 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=(',', ': ')))
Efter ett lyckat anrop bör du se följande svar. Till skillnad från anropet translate till slutpunkten breaksentence returnerar bara teckenantalet för källtexten i en matris med namnet sentLen.
Med slutpunkten kan du hämta alternativa översättningar för ett ord eller en fras. När du till exempel översätter ordet "sunshine" från en till esreturnerar den här slutpunkten "luz solar", "rayos solares" och "soleamiento", "sol" och "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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
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));
})
import requests, uuid, json
# 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=(',', ': ')))
Efter ett lyckat anrop bör du se följande svar. Nu ska vi undersöka svaret närmare eftersom JSON är mer komplext än några av de andra exemplen i den här artikeln. Matrisen translations innehåller en lista över översättningar. Varje objekt i den här matrisen innehåller en konfidenspoäng (confidence), texten som optimerats för slutanvändarvisning (displayTarget), normaliserad text (normalizedText), delen av tal (posTag) och information om tidigare översättning (backTranslations). Mer information om svaret finns i Ordlistesökning
När du har kört en ordlistesökning skickar du käll- och översättningstexten dictionary/examples till slutpunkten för att hämta en lista med exempel som visar båda termerna i kontexten för en mening eller fras. Om du bygger på föregående exempel använder normalizedTextnormalizedTarget du och från ordlistesökningssvaret som text respektive translation . Parametrarna källspråk (from) och utdatamål (to) krävs.
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
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));
})
import requests, uuid, json
# 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=(',', ': ')))
Efter ett lyckat anrop bör du se följande svar. Mer information om svaret finns i Ordlistesökning
[
{
"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."
}
]
}
]
Felsökning
Vanliga HTTP-statuskoder
HTTP-statuskod
beskrivning
Möjlig orsak
200
OK
Begäran lyckades.
400
Felaktig förfrågan
En obligatorisk parameter saknas, är tom eller null. Eller så är värdet som skickas till en obligatorisk eller valfri parameter ogiltigt. Ett vanligt problem är en rubrik som är för lång.
401
Behörighet saknas
Begäran är inte auktoriserad. Kontrollera att din nyckel eller token är giltig och i rätt region. Se ävenAutentisering.
429
För många begäranden
Du har överskridit kvoten eller antalet begäranden som tillåts för din prenumeration.
502
Felaktig gateway
Problem på nätverks- eller serversidan. Kan också indikera ogiltiga rubriker.
Java-användare
Om du stöter på anslutningsproblem kan det bero på att TLS/SSL-certifikatet har upphört att gälla. Lös problemet genom att installera DigiCertGlobalRootG2.crt i din privata butik.