In deze handleiding leert u hoe u de REST API's van de Translator-service gebruikt. U begint met de basisvoorbeelden en gaat vervolgens verder met een aantal belangrijke configuratie-opties die vaak worden gebruikt tijdens de ontwikkeling, waaronder:
Een Azure AI-resource voor meerdere services of Translator. Zodra u uw Azure-abonnement hebt, maakt u een enkele service of een resource voor meerdere services , in Azure Portal, om uw sleutel en eindpunt op te halen. Nadat de app is geïmplementeerd, selecteert u Ga naar resource.
U kunt de gratis prijscategorie (F0) gebruiken om de service uit te proberen en later upgraden naar een betaalde laag voor productie.
U hebt de sleutel en het eindpunt van de resource nodig om uw toepassing te verbinden met de Translator-service. Later plakt u uw sleutel en eindpunt in de codevoorbeelden. U vindt deze waarden op de pagina Sleutels en eindpunten van Azure Portal:
Belangrijk
Vergeet niet de sleutel uit uw code te verwijderen wanneer u klaar bent, en maak deze sleutel nooit openbaar. Gebruik voor productie een veilige manier om uw referenties op te slaan en te openen, zoals Azure Key Vault. Zie de beveiliging van Azure AI-services voor meer informatie.
Kopteksten
Als u de Translator-service wilt aanroepen via de REST API, moet u ervoor zorgen dat de volgende headers bij elke aanvraag zijn opgenomen. Maak u geen zorgen, we nemen de headers op in de voorbeeldcode in de volgende secties.
Koptekst
Weergegeven als
Conditie
Ocp-Apim-Subscription-Key
Uw Translator-servicesleutel vanuit Azure Portal.
Vereist
Ocp-Apim-Subscription-Region
De regio waar uw resource is gemaakt.
Vereist bij het gebruik van een Azure AI-resource voor meerdere services of regionale (geografische) resources, zoals VS - west.
Optioneel wanneer u een Translator-resource met één service gebruikt.
Content-Type
Het inhoudstype van de nettolading. De geaccepteerde waarde is application/json of charset=UTF-8.
Vereist
Lengte van inhoud
De lengte van de aanvraagbody .
Optioneel
X-ClientTraceId
Een door de client gegenereerde GUID om de aanvraag op unieke wijze te identificeren. U kunt deze header weglaten als u de tracerings-id in de querytekenreeks opneemt met behulp van een queryparameter met de naam ClientTraceId.
Voer op de pagina Een nieuw project maken de console in het zoekvak in. Kies de consoletoepassingssjabloon en kies vervolgens Volgende.
Voer translator_text_app in het dialoogvenster Uw nieuwe project configureren het vak Projectnaam in. Laat het selectievakje Oplossing en project in dezelfde map plaatsen uitgeschakeld en selecteer Volgende.
Zorg ervoor dat .NET 6.0 (langetermijnondersteuning) is geselecteerd in het dialoogvenster Aanvullende informatie. Laat het selectievakje 'Geen instructies op het hoogste niveau gebruiken' uitgeschakeld en selecteer Maken.
Het Newtonsoft.json-pakket installeren met NuGet
Klik met de rechtermuisknop op uw translator_quickstart project en selecteer NuGet-pakketten beheren... .
Selecteer het tabblad Bladeren en typ Newtonsoft.
Selecteer Installeren in het juiste venster van Package Manager en voeg het pakket toe aan uw project.
Uw toepassing bouwen
Notitie
Vanaf .NET 6 genereren nieuwe projecten met behulp van de console sjabloon een nieuwe programmastijl die verschilt van eerdere versies.
De nieuwe uitvoer maakt gebruik van recente C#-functies die de code vereenvoudigen die u moet schrijven.
Wanneer u de nieuwere versie gebruikt, hoeft u alleen de hoofdtekst van de Main methode te schrijven. U hoeft geen instructies op het hoogste niveau, globaal gebruik van instructies of impliciet gebruik van instructies op te nemen.
Verwijder de bestaande code, inclusief de regel Console.WriteLine("Hello World!"). Kopieer en plak de codevoorbeelden in het Program.cs-bestand van uw toepassing. Zorg ervoor dat u voor elk codevoorbeeld de sleutel- en eindpuntvariabelen bijwerkt met waarden uit uw Azure Portal Translator-exemplaar.
Zodra u een gewenst codevoorbeeld aan uw toepassing hebt toegevoegd, kiest u de groene startknop naast formRecognizer_quickstart om uw programma te bouwen en uit te voeren, of drukt u op F5.
Download de Go-toepassingsversie voor uw besturingssysteem.
Zodra het downloaden is voltooid, voert u het installatieprogramma uit.
Open een opdrachtprompt en voer het volgende in om te bevestigen dat Go is geïnstalleerd:
go version
Maak in een consolevenster (zoals cmd, PowerShell of Bash) een nieuwe map voor uw app met de naam translator-text-app en navigeer ernaartoe.
Maak een nieuw GO-bestand met de naam text-translator.go vanuit de map translator-text-app .
Kopieer en plak de codevoorbeelden in het bestand text-translator.go . Zorg ervoor dat u de sleutelvariabele bijwerkt met de waarde van uw Azure Portal Translator-exemplaar.
Nadat u een codevoorbeeld aan uw toepassing hebt toegevoegd, kan uw Go-programma worden uitgevoerd in een opdracht- of terminalprompt. Zorg ervoor dat het pad van de prompt is ingesteld op de map translator-text-app en gebruik de volgende opdracht:
Visual Studio Code biedt een Coderingspakket voor Java voor Windows en macOS. Het coderingspakket is een bundel VS Code, de Java Development Kit (JDK) en een verzameling voorgestelde extensies van Microsoft. Het coderingspakket kan ook worden gebruikt om een bestaande ontwikkelomgeving op te lossen.
Als u VS Code en het Coderingspakket voor Java gebruikt, installeert u de Gradle voor Java-extensie.
Als u Visual Studio Code niet gebruikt, controleert u of het volgende is geïnstalleerd in uw ontwikkelomgeving:
Maak in het consolevenster (zoals cmd, PowerShell of Bash) een nieuwe map voor uw app met de naam translator-text-app en navigeer ernaartoe.
mkdir translator-text-app && translator-text-app
mkdir translator-text-app; cd translator-text-app
Voer de gradle init opdracht uit vanuit de map translator-text-app. Met deze opdracht maakt u essentiële buildbestanden voor Gradle, waaronder build.gradle.kts, die tijdens runtime wordt gebruikt om uw toepassing te maken en te configureren.
gradle init --type basic
Wanneer u wordt gevraagd om een DSL te kiezen, selecteert u Kotlin.
Accepteer de standaardprojectnaam (translator-text-app) door Return of Enter te selecteren.
Notitie
Het kan enkele minuten duren voordat de hele toepassing is gemaakt, maar binnenkort ziet u verschillende mappen en bestanden, waaronder build-gradle.kts.
Voer vanuit de map translator-text-app de volgende opdracht uit:
mkdir -p src/main/java
U maakt de volgende mapstructuur:
Navigeer naar de map en maak een bestand met de java naam TranslatorText.java.
Tip
U kunt een nieuw bestand maken met behulp van PowerShell.
Open een PowerShell-venster in uw projectmap door Shift ingedrukt te houden en met de rechtermuisknop op de map te klikken.
Typ de volgende opdracht TranslatorText.java.
U kunt ook een nieuw bestand maken in uw IDE met de naam TranslatorText.java en opslaan in de java map.
Kopieer en plak het codevoorbeeldbestand TranslatorText.java . Zorg ervoor dat u de sleutel bijwerkt met een van de sleutelwaarden van uw Azure Portal Translator-exemplaar.
Zodra u een codevoorbeeld aan uw toepassing hebt toegevoegd, gaat u terug naar de hoofdmap van het project: translator-text-app, opent u een consolevenster en voert u de volgende opdrachten in:
Bouw uw toepassing met de build opdracht:
gradle build
Voer uw toepassing uit met de run opdracht:
gradle run
Als deze niet is geïnstalleerd in uw ontwikkelomgeving, downloadt u de nieuwste versie van Node.js. Node Pakketbeheer (npm) is opgenomen in de Node.js-installatie.
Maak en navigeer in een consolevenster (zoals cmd, PowerShell of Bash) naar een nieuwe map voor uw app met de naam translator-text-app.
mkdir translator-text-app && cd translator-text-app
mkdir translator-text-app; cd translator-text-app
Voer de npm init-opdracht uit om de toepassing te initialiseren en uw project te initialiseren.
npm init
Geef de kenmerken van uw project op met behulp van de prompts die worden weergegeven in de terminal.
De belangrijkste kenmerken zijn naam, versienummer en toegangspunt.
U wordt aangeraden de naam van het toegangspunt op te geven index.js . De beschrijving, testopdracht, GitHub-opslagplaats, trefwoorden, auteurs en licentiegegevens zijn optionele kenmerken. Ze kunnen voor dit project worden overgeslagen.
Accepteer de suggesties tussen haakjes door Return of Enter te selecteren.
Nadat u de aanwijzingen hebt voltooid, wordt er een package.json bestand gemaakt in de map translator-text-app.
Open een consolevenster en gebruik npm om de HTTP-bibliotheek en uuid het axios pakket te installeren:
npm install axios uuid
Maak het index.js bestand in de toepassingsmap.
Tip
U kunt een nieuw bestand maken met behulp van PowerShell.
Open een PowerShell-venster in uw projectmap door Shift ingedrukt te houden en met de rechtermuisknop op de map te klikken.
Typ de volgende opdracht New-Item index.js.
U kunt ook een nieuw bestand maken met de naam index.js in uw IDE en opslaan in de translator-text-app map.
Kopieer en plak de codevoorbeelden in uw index.js bestand. Zorg ervoor dat u de sleutelvariabele bijwerkt met de waarde van uw Azure Portal Translator-exemplaar.
Nadat u het codevoorbeeld aan uw toepassing hebt toegevoegd, voert u het volgende uit:
Navigeer naar de toepassingsmap (translator-text-app).
Typ de volgende opdracht in uw terminal:
node index.js
Als u deze niet in uw ontwikkelomgeving hebt, installeert u de nieuwste versie van Python 3.x. Het Python-installatiepakket (pip) is opgenomen in de Python-installatie.
Open een terminalvenster en gebruik pip om de aanvraagbibliotheek en het uuid0-pakket te installeren:
pip install requests uuid
Notitie
We gebruiken ook een ingebouwd Python-pakket met de naam json. Het wordt gebruikt om met JSON-gegevens te werken.
Maak een nieuw Python-bestand met de naam text-translator.py in uw favoriete editor of IDE.
Voeg het volgende codevoorbeeld toe aan uw text-translator.py bestand. Zorg ervoor dat u de sleutel bijwerkt met een van de waarden van uw Azure Portal Translator-exemplaar.
Zodra u een gewenst codevoorbeeld aan uw toepassing hebt toegevoegd, bouwt en voert u het programma uit:
Navigeer naar het text-translator.py-bestand .
Typ de volgende opdracht in uw console:
python text-translator.py
Belangrijk
Voor de voorbeelden in deze handleiding zijn in code vastgelegde sleutels en eindpunten vereist.
Vergeet niet de sleutel uit uw code te verwijderen wanneer u klaar bent, en maak deze sleutel nooit openbaar.
Overweeg om voor productie een veilige manier te gebruiken voor het opslaan en openen van uw referenties. Zie Beveiliging van Azure AI-services voor meer informatie.
Tekst vertalen
De belangrijkste functie van de Translator-service is het vertalen van tekst. In deze sectie bouwt u een aanvraag die één bron () gebruikt en twee uitvoer (fromto). Vervolgens bekijken we enkele parameters die kunnen worden gebruikt om zowel de aanvraag als het antwoord aan te passen.
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=(',', ': ')))
Na een geslaagde aanroep ziet u het volgende antwoord:
[
{
"translations":[
{
"text":"Halo, rafiki! Ulifanya nini leo?",
"to":"sw"
},
{
"text":"Ciao, amico! Cosa hai fatto oggi?",
"to":"it"
}
]
}
]
Als u vertaling nodig hebt, maar de taal van de tekst niet kent, kunt u de taaldetectiebewerking gebruiken. Er zijn verschillende manieren om de taal van de brontekst te identificeren. In deze sectie leert u hoe u taaldetectie gebruikt met behulp van het translate eindpunt en het detect eindpunt.
Brontaal detecteren tijdens de vertaling
Als u de parameter niet opneemt in uw from vertaalaanvraag, probeert de Translator-service de taal van de brontekst te detecteren. In het antwoord krijgt u de gedetecteerde taal (language) en een betrouwbaarheidsscore (score). Hoe dichter het score is, 1.0betekent dat er meer vertrouwen is dat de detectie juist is.
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=(',', ': ')))
Na een geslaagde aanroep ziet u het volgende antwoord:
[
{
"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"
}
]
}
]
Brontaal detecteren zonder vertaling
Het is mogelijk de Translator-service te gebruiken om de taal van de brontekst te detecteren zonder een vertaling uit te voeren. Hiervoor gebruikt u het /detect eindpunt.
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=(',', ': ')))
Het /detect eindpuntantwoord bevat alternatieve detecties en geeft aan of de vertaling en transliteratie worden ondersteund voor alle gedetecteerde talen. Na een geslaagde aanroep ziet u het volgende antwoord:
Transliteratie is het proces waarbij een woord of woordgroep van het script (alfabet) van de ene taal naar de andere wordt omgezet op basis van de fonetische gelijkenis. U kunt bijvoorbeeld transliteratie gebruiken om ' สวัสดี ' (thai) om te zetten naar 'sawatdi' (latn). Er is meer dan één manier om transliteratie uit te voeren. In deze sectie leert u hoe u taaldetectie gebruikt met behulp van het translate eindpunt en het transliterate eindpunt.
Transliteratie tijdens de vertaling
Als u tekst naar een taal wilt vertalen die gebruikmaakt van een ander alfabet (of fonemen) dan uw bron, moet u de tekst mogelijk eerst transliteren. In dit voorbeeld vertalen we 'Hello' van het Engels naar het Thais. Naast de vertaling in het Thais krijgt u een transliteratie van de vertaalde woordgroep met behulp van het Latijnse alfabet.
Als u een transliteratie wilt met het translate-eindpunt, gebruikt u de parameter toScript .
using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static readonly string location = "<YOUR-RESOURCE-LOCATION>";
static async Task Main(string[] args)
{
// Output language defined as parameter, with toScript set to latn
string route = "/translate?api-version=3.0&to=th&toScript=latn";
string textToTransliterate = "Hello, friend! What did you do today?";
object[] body = new object[] { new { Text = textToTransliterate } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// Send the request and get response.
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
// Read response as a string.
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
}
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=(',', ': ')))
Na een geslaagde aanroep ziet u het volgende antwoord. Houd er rekening mee dat het antwoord van het translate-eindpunt de gedetecteerde brontaal bevat met een betrouwbaarheidsscore, een vertaling in het alfabet van de uitvoertaal en een transliteratie in het Latijnse alfabet.
U kunt ook het transliterate-eindpunt gebruiken voor een transliteratie. Wanneer u het eindpunt voor transliteratie gebruikt, moet u de brontaal (language), het bronscript/-alfabet (fromScript) en het uitvoerscript/-alfabet (toScript) als parameters opgeven. In dit voorbeeld krijgen we de transliteratie voor สวัสดีเพื่อน! วันนี้คุณทำอะไร.
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=(',', ': ')))
Na een geslaagde aanroep ziet u het volgende antwoord. In tegenstelling tot de aanroep van het translate-eindpunt, retourneert transliterate alleen de text en de uitvoer script.
Met de Translator-service kunt u het aantal tekens voor een zin of reeks zinnen bepalen. Het antwoord wordt geretourneerd als een matrix, met het aantal tekens dat voor elke zin is gedetecteerd. U kunt de zinslengte bepalen met de translate- en breaksentence-eindpunten.
Zinslengte bepalen tijdens vertaling
U kunt het aantal tekens voor zowel de brontekst als de vertaaluitvoer bepalen met behulp van het translate-eindpunt. Als u de zinslengte wilt retourneren (srcSenLen en transSenLen), moet u de parameter includeSentenceLength instellen op 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=(',', ': ')))
Na een geslaagde aanroep ziet u het volgende antwoord. Naast de gedetecteerde brontaal en vertaling krijgt u het aantal tekens voor elke gedetecteerde zin voor zowel de bron (srcSentLen) als de vertaling (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=(',', ': ')))
Na een geslaagde aanroep ziet u het volgende antwoord. In tegenstelling tot de aanroep van het translate-eindpunt, retourneert breaksentence alleen het aantal tekens voor de brontekst in een matrix met de naam sentLen.
Opzoeken in woordenlijst (alternatieve vertalingen)
Met het eindpunt kunt u alternatieve vertalingen voor een woord of woordgroep verkrijgen. Als u bijvoorbeeld het woord 'zonneschijn' van en naar esvertaalt, retourneert dit eindpunt 'luz solar,' ', 'rayos solares' en 'soleamiento', 'sol' en '.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=(',', ': ')))
Na een geslaagde aanroep ziet u het volgende antwoord. Laten we het antwoord nauwkeuriger bekijken, omdat de JSON complexer is dan enkele van de andere voorbeelden in dit artikel. De translations-matrix bevat een lijst met vertalingen. Elk object in deze matrix bevat een betrouwbaarheidsscore (confidence), de tekst die is geoptimaliseerd voor weergave aan eindgebruikers (displayTarget), de genormaliseerde tekst (normalizedText), de woordsoort (posTag) en informatie over de vorige vertaling (backTranslations). Zie Opzoeken in woordenlijst voor meer informatie over het antwoord
Voorbeelden van woordenlijsten (vertalingen met context)
Nadat u een opzoekactie voor woordenlijsten hebt uitgevoerd, geeft u de bron- en vertaaltekst door aan het dictionary/examples eindpunt om een lijst met voorbeelden weer te geven waarin beide termen in de context van een zin of zin worden weergegeven. Verderop in het vorige voorbeeld gebruikt u het antwoord voor normalizedTarget opzoeken in woordenlijst normalizedText als text en translation respectievelijk. De parameters voor de brontaal (from) en het uitvoerdoel (to) zijn vereist.
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=(',', ': ')))
[
{
"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."
}
]
}
]
Probleemoplossing
Algemene HTTP-statuscodes
HTTP-statuscode
Beschrijving
Mogelijke reden
200
OK
De aanvraag is geslaagd.
400
Onjuiste aanvraag
Een vereiste parameter ontbreekt, leeg of null. Of de waarde die is doorgegeven aan een vereiste of optionele parameter, is ongeldig. Een veelvoorkomend probleem is een header die te lang is.
401
Niet geautoriseerd
De aanvraag is niet geautoriseerd. Controleer of uw sleutel of token geldig is en zich in de juiste regio bevindt. Zie ookVerificatie.
429
Te veel aanvragen
U hebt het quotum of de frequentie van aanvragen overschreden die zijn toegestaan voor uw abonnement.
502
Ongeldige gateway
Probleem aan de netwerk- of serverzijde. Kan ook duiden op ongeldige headers.
Java-gebruikers
Als u verbindingsproblemen ondervindt, kan het zijn dat uw TLS/SSL-certificaat is verlopen. U kunt dit probleem oplossen door de DigiCertGlobalRootG2.crt te installeren in uw privé-archief.