In deze quickstart leert u hoe u de Translator-service via REST kunt gebruiken. U begint met de basisvoorbeelden en gaat vervolgens verder met een aantal belangrijke configuratie-opties die vaak worden gebruikt tijdens de ontwikkeling, waaronder:
Zodra u een Azure-abonnement hebt, maakt u een Translator-resource in Azure Portal om uw sleutel en eindpunt op te halen. Nadat de app is geïmplementeerd, selecteert u Ga naar resource.
U hebt de sleutel en het eindpunt nodig van de resource om de toepassing te verbinden met de Translator-service. Later in de quickstart plakt u uw sleutel en eindpunt in de onderstaande code. U vindt deze waarden op de pagina Azure Portal sleutels en eindpunt:
U kunt de gratis prijscategorie (F0) gebruiken om de service uit te proberen en later upgraden naar een betaalde laag voor productie.
Wanneer u de Translator-service via REST aanroept, moet u ervoor zorgen dat de volgende headers in elke aanvraag zijn opgenomen. U vindt de headers in de voorbeeldcode in de volgende secties.
De vereiste aanvraagheader als er een Cognitive Services-resource wordt gebruikt. Optioneel als er een Translator-resource wordt gebruikt. Ocp-Apim-Subscription-Region
Vereiste aanvraagheader. Hiermee geeft u het inhoudstype van de payload op. De geaccepteerde waarde is application/json; charset=UTF-8.
Content-Length
Vereiste aanvraagheader. De lengte van de aanvraagtekst.
X-ClientTraceId
Optioneel. 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 queryreeks opneemt middels een queryparameter met de naam ClientTraceId.
Sleutels en eindpunten
De voorbeelden op deze pagina gebruiken voor het gemak in code vastgelegde sleutels en eindpunten. 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 het artikel Cognitive Services Beveiliging voor meer informatie.
Tekst vertalen
De belangrijkste functie van de Translator-service is het vertalen van tekst. In deze sectie maakt u een aanvraag met één bron (from) en twee uitvoerwaarden (to). Vervolgens bekijken we enkele parameters die kunnen worden gebruikt om zowel de aanvraag als het antwoord aan te passen.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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=de&to=it";
string textToTranslate = "Hello, world!";
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", subscriptionKey);
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() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("from", "en")
q.Add("to", "de")
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: "Hello, world!"},
}
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", subscriptionKey)
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)
}
Als u weet dat u een vertaling nodig hebt, maar de taal van de tekst die naar de Translator-service wordt verzonden, niet kent, kunt u de taaldetectiefunctie gebruiken. Er zijn verschillende manieren om de taal van de brontekst te identificeren. In deze sectie leert u hoe u taaldetectie kunt gebruiken met behulp van het translate-eindpunt en het detect-eindpunt.
Brontaal detecteren tijdens de vertaling
Als u de parameter from niet in uw vertaalaanvraag opneemt, probeert de Translator-service de taal van de brontekst zelf te detecteren. In het antwoord wordt de gedetecteerde taal (language) en een betrouwbaarheidsscore (score) weergeven. Hoe dichter de score bij 1.0 ligt, hoe groter de kans is dat de gedetecteerde taal juist is.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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=de&to=it";
string textToTranslate = "Hello, world!";
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", subscriptionKey);
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() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("to", "de")
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: "Hello, world!"},
}
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", subscriptionKey)
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)
}
Het is mogelijk de Translator-service te gebruiken om de taal van de brontekst te detecteren zonder een vertaling uit te voeren. U kunt dit doen door het /detect-eindpunt te gebruiken.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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 = "Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.";
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", subscriptionKey);
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() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/detect?api-version=3.0"
// Build the request URL. See: https://golang.org/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: "Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal."},
}
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", subscriptionKey)
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 Detect {
private static String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/detect")
.addQueryParameter("api-version", "3.0")
.build();
// 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\": \"Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", subscriptionKey)
.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 {
Detect detectRequest = new Detect();
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');
var subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/detect',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0'
},
data: [{
'text': 'Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your subscription key and endpoint
subscription_key = "YOUR_SUBSCRIPTION_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/detect'
constructed_url = endpoint + path
params = {
'api-version': '3.0'
}
constructed_url = endpoint + path
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'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': 'Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.'
}]
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=(',', ': ')))
Wanneer het /detect-eind punt wordt gebruikt, bevat het antwoord alternatieve detecties en kunt u zien of vertaling en transliteratie worden ondersteund voor de 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 kunt gebruiken 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 .
Notitie
Zie Taalondersteuning voor een volledige lijst met beschikbare talen en transliteratieopties.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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";
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", subscriptionKey);
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() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://golang.org/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"},
}
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", subscriptionKey)
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)
}
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 gaan we een transliteratie maken van สวัสดี.
Notitie
Zie Taalondersteuning voor een volledige lijst met beschikbare talen en transliteratieopties.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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 = "/translate?api-version=3.0&to=th&toScript=latn";
string textToTransliterate = "Hello";
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", subscriptionKey);
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() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/transliterate?api-version=3.0"
// Build the request URL. See: https://golang.org/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", subscriptionKey)
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)
}
Na een geslaagde aanroep ziet u het volgende antwoord. In tegenstelling tot de aanroep van het translate-eindpunt, retourneert transliterate alleen de script en de uitvoer text.
[
{
"script": "latn",
"text": "sawatdi"
}
]
Zinslengte bepalen
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 System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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", subscriptionKey);
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() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://golang.org/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", subscriptionKey)
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 Translate {
private static String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/translate")
.addQueryParameter("api-version", "3.0")
.addQueryParameter("to", "es")
.addQueryParameter("includeSentenceLength", "true")
.build();
// 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", subscriptionKey)
.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 {
Translate translateRequest = new Translate();
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');
var subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/translate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0',
'to': 'es',
'includeSentenceLength': true
},
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 subscription key and endpoint
subscription_key = "YOUR_SUBSCRIPTION_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'to': 'es',
'includeSentenceLength': True
}
constructed_url = endpoint + path
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'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 System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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", subscriptionKey);
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() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/breaksentence?api-version=3.0"
// Build the request URL. See: https://golang.org/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", subscriptionKey)
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 BreakSentence {
private static String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/breaksentence")
.addQueryParameter("api-version", "3.0")
.build();
// 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", subscriptionKey)
.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 {
BreakSentence breakSentenceRequest = new BreakSentence();
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');
var subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/breaksentence',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0'
},
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 subscription key and endpoint
subscription_key = "YOUR_SUBSCRIPTION_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/breaksentence'
constructed_url = endpoint + path
params = {
'api-version': '3.0'
}
constructed_url = endpoint + path
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'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. Wanneer bijvoorbeeld het woord 'haaien' wordt vertaald van en naar es, retourneert dit eindpunt zowel 'tiburón' als 'escualo'.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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 = "shark";
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", subscriptionKey);
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() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/dictionary/lookup?api-version=3.0"
// Build the request URL. See: https://golang.org/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: "shark"},
}
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", subscriptionKey)
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)
}
Na een geslaagde aanroep ziet u het volgende antwoord. We zullen hier wat uitgebreider op ingaan, omdat de JSON complexer is dan die van 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 woord heeft opgezocht in de woordenlijst, kunt u de brontekst en vertaling doorgeven aan het dictionary/examples-eindpunt om een lijst met voorbeelden te verkrijgen waarin beide termen in de context van een zin of woordgroep worden weergegeven. Op basis van het vorige voorbeeld gebruikt u de normalizedText en normalizedTarget uit het antwoord van de zoekopdracht als text en translation. De parameters voor de brontaal (from) en het uitvoerdoel (to) zijn vereist.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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 = "Shark", Translation = "tiburón" } } ;
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", subscriptionKey);
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() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/dictionary/examples?api-version=3.0"
// Build the request URL. See: https://golang.org/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: "Shark",
Translation: "tiburón",
},
}
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", subscriptionKey)
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)
}
[
{
"examples": [
{
"sourcePrefix": "More than a match for any ",
"sourceSuffix": ".",
"sourceTerm": "shark",
"targetPrefix": "Más que un fósforo para cualquier ",
"targetSuffix": ".",
"targetTerm": "tiburón"
},
{
"sourcePrefix": "Same with the mega ",
"sourceSuffix": ", of course.",
"sourceTerm": "shark",
"targetPrefix": "Y con el mega ",
"targetSuffix": ", por supuesto.",
"targetTerm": "tiburón"
},
{
"sourcePrefix": "A ",
"sourceSuffix": " ate it.",
"sourceTerm": "shark",
"targetPrefix": "Te la ha comido un ",
"targetSuffix": ".",
"targetTerm": "tiburón"
}
],
"normalizedSource": "shark",
"normalizedTarget": "tiburón"
}
]
Problemen oplossen
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 wordt doorgegeven aan een vereiste of optionele parameter is ongeldig. Een veelvoorkomende probleem is een header die te lang is.
401
Niet geautoriseerd
De aanvraag is niet geautoriseerd. Controleer of uw abonnementssleutel of token geldig is en in de juiste regio. Zie ookVerificatie.
429
Te veel aanvragen
U hebt het quotum of het aantal toegestane aanvragen voor uw abonnement overschreden.
502
Slechte gateway
Netwerk- of serverprobleem. Kan ook duiden op ongeldige headers.
Java-gebruikers
Als u verbindingsproblemen ondervindt, is uw SSL-certificaat mogelijk verlopen. U kunt dit probleem oplossen door de DigiCertGlobalRootG2.crt te installeren in uw privé-archief.