Dans ce guide pratique, vous apprenez à utiliser l’API REST du service Translator. Vous commencez avec des exemples basiques, puis vous passez à quelques options de configuration principales couramment utilisées pendant le développement, notamment :
Une ressource multiservice Azure AI ou Translator. Une fois que vous avez votre abonnement Azure, créez une ressource monoservice ou multiservice dans le portail Azure pour obtenir votre clé et votre point de terminaison. À la fin du déploiement, sélectionnez Accéder à la ressource.
Vous pouvez utiliser le niveau tarifaire Gratuit (F0) pour tester le service, puis passer par la suite à un niveau payant pour la production.
Vous aurez besoin de la clé et du point de terminaison de la ressource pour connecter votre application au service Translator. Plus loin, vous collez votre clé et votre point de terminaison dans les exemples de code. Vous pouvez trouver ces valeurs sur la page Clés et Points de terminaison du portail Azure :
Important
N’oubliez pas de supprimer la clé de votre code une fois que vous avez terminé, et ne la postez jamais publiquement. Pour la production, utilisez un moyen sécurisé de stocker et d’accéder à vos informations d’identification comme Azure Key Vault. Pour plus d’informations, consultez la sécurité d’Azure AI services.
En-têtes
Pour appeler le service Translator par le biais de l’API REST, vous devez vérifier que les en-têtes suivants sont inclus dans chaque requête. Ne vous inquiétez pas, nous incluons ces en-têtes dans l’exemple de code dans les sections suivantes.
En-tête
Valeur
Condition
Ocp-Apim-Subscription-Key
Votre clé de service Traducteur à partir du Portail Azure.
Obligatoire
Ocp-Apim-Subscription-Region
Région dans laquelle votre ressource a été créée.
Obligatoire lors de l’utilisation d’une ressource multiservice Azure AI ou d’une ressource régionale (géographique) tel que USA Ouest.
Facultatif lorsque vous utilisez une ressource Translator monoservice.
Content-Type
Type de contenu de la charge utile. Les valeurs acceptées sont application/json ou charset=UTF-8.
Obligatoire
Content-Length
Longueur du corps de la demande.
Facultatif
X-ClientTraceId
GUID généré par le client pour identifier de façon unique la demande. Vous pouvez omettre cet en-tête si vous incluez l’ID de trace dans la chaîne de requête à l’aide d’un paramètre de requête nommé ClientTraceId.
Dans la page de démarrage, choisissez Créer un projet.
Dans la page Créer un nouveau projet, entrez console dans la zone de recherche. Choisissez le modèle Application console, puis choisissez Suivant.
Dans la fenêtre de dialogue Configurer votre nouveau projet, entrez translator_text_app dans la zone Nom de projet. Laissez la case à cocher « Placer la solution et le projet dans le même répertoire » désactivée, puis sélectionnez Suivant.
Dans la fenêtre de dialogue Informations supplémentaires, vérifiez que .NET 6.0 (Support à long terme) est sélectionné. Laissez la case à cocher « Ne pas utiliser d’instructions de niveau supérieur » décochée et sélectionnez Créer.
Installer le package Newtonsoft.json avec NuGet
Cliquez avec le bouton droit sur votre projet translator_quickstart et sélectionnez Gérer les packages NuGet.
Sélectionnez l’onglet Parcourir et tapez Newtonsoft.
Sélectionnez Installer dans la fenêtre du gestionnaire de package appropriée et ajouter le package à votre projet.
Générer votre application
Notes
À compter de .NET 6, de nouveaux projets utilisant le modèle console génèrent un nouveau style de programme qui diffère des versions précédentes.
La nouvelle sortie utilise des fonctionnalités C# récentes qui simplifient le code que vous devez écrire.
Lorsque vous utilisez la version la plus récente, vous devez uniquement écrire le corps de la Main méthode. Vous n’avez pas besoin d’inclure des instructions de niveau supérieur, des directives globales à l’aide de directives ou des directives implicites.
Supprimez le code préexistant, y compris la ligne Console.WriteLine("Hello World!"). Copiez et collez les exemples de code dans le fichier Program.cs de votre application. Pour chaque exemple de code, veillez à mettre à jour les variables de clé et de point de terminaison avec les valeurs de votre instance Translator dans le Portail Azure.
Une fois que vous ajoutez un exemple de code à votre application, choisissez le bouton vert Démarrer en regard de formRecognizer_quickstart pour générer et exécuter votre programme, ou appuyez sur F5.
Téléchargez la version de l’application Go pour votre système d'exploitation.
Une fois le téléchargement terminé, exécutez le programme d’installation.
Ouvrez une invite de commandes et entrez ce qui suit pour confirmer que Go a été installé :
go version
Dans une fenêtre de console (par exemple, cmd, PowerShell ou Bash), créez le répertoire translator-text-app pour votre application et accédez-y.
Créez un fichier GO nommé text-translator.go à partir du répertoire translator-text-app.
Copiez et collez les exemples de code dans votre fichier text-translator.go. Veillez à mettre à jour la variable de clé avec la valeur de votre instance Translator du Portail Azure.
Une fois que vous avez ajouté un exemple de code à votre application, votre programme Go peut être exécuté dans une invite de commandes ou de terminal. Vérifiez que le chemin d’accès de votre invite est défini sur le dossier translator-text-app et utilisez la commande suivante :
Visual Studio Code offre un pack de programmation pour Java pour Windows et macOS. Le pack de programmation est un bundle de VS Code, le Kit de développement Java (JDK) et une collection d’extensions suggérées par Microsoft. Le Pack de programmation peut également être utilisé pour corriger un environnement de développement existant.
Si vous utilisez VS Code et le Pack de programmation pour Java, installez l’extension Gradle pour Java.
Si vous n’utilisez pas Visual Studio Code, vérifiez que les éléments suivants sont installés dans votre environnement de développement :
Dans une fenêtre de console (par exemple, cmd, PowerShell ou Bash), créez le répertoire translator-text-app pour votre application et accédez-y.
mkdir translator-text-app && translator-text-app
mkdir translator-text-app; cd translator-text-app
Exécutez la commande gradle init à partir du répertoire translator-text-app. Cette commande crée des fichiers de build essentiels pour Gradle, notamment build.gradle.kts, qui est utilisé au moment de l’exécution pour créer et configurer votre application.
gradle init --type basic
Quand vous êtes invité à choisir un DSL, sélectionnez Kotlin.
Acceptez le nom du projet par défaut (translator-text-app) en sélectionnant Retour ou Entrée.
Notes
La création de l’ensemble de l’application peut prendre quelques minutes, mais vous devriez bientôt voir plusieurs dossiers et fichiers, notamment build-gradle.kts.
Mettez à jour build.gradle.kts à l’aide du code suivant :
À partir du répertoire translator-text-app, exécutez la commande suivante :
mkdir -p src/main/java
Vous créez la structure de répertoires suivante :
Accédez au répertoire java et créez un fichier nommé TranslatorText.java.
Conseil
Vous pouvez créer un nouveau fichier à l’aide de PowerShell.
Ouvrez une fenêtre PowerShell dans le répertoire de votre projet en maintenant la touche Maj enfoncée et en cliquant avec le bouton droit sur le dossier.
Tapez la commande New-Item TranslatorText.java.
Vous pouvez également créer un fichier dans votre IDE nommé TranslatorText.java et l’enregistrer dans le répertoire java.
Copiez et collez le fichier TranslatorText.java d’exemples de code. Veillez à mettre à jour la clé avec l’une des valeurs de clé de votre instance Translator du Portail Azure.
Une fois que vous avez ajouté un exemple de code à votre application, revenez à votre répertoire de projet principal (translator-text-app), ouvrez une fenêtre de console et entrez les commandes suivantes :
Générez votre application avec la commande build :
gradle build
Exécutez votre application avec la commande run :
gradle run
S’il n’est pas installé dans votre environnement de développement, téléchargez la dernière version de Node.js. Node Package Manager (npm) est inclus dans l’installation Node.js.
Dans une fenêtre de console (par exemple, cmd, PowerShell ou Bash), créez un répertoire translator-text-app pour votre application et accédez-y.
mkdir translator-text-app && cd translator-text-app
mkdir translator-text-app; cd translator-text-app
Exécutez la commande npm init pour initialiser l’application et échafauder votre projet.
npm init
Spécifiez les attributs de votre projet à l’aide des invites qui s’affichent dans le terminal.
Les attributs les plus importants sont le nom, le numéro de version et le point d’entrée.
Nous vous recommandons de conserver index.js comme nom du point d’entrée. La description, la commande de test, le référentiel GitHub, les mots clés, l’auteur et les informations de licence sont des attributs facultatifs. Vous pouvez les ignorer pour ce projet.
Acceptez les suggestions entre parenthèses en sélectionnant Retour ou Entrée.
Une fois que vous avez répondu aux invites, un fichier package.json est créé dans votre répertoire translator-text-app.
Ouvrez une fenêtre de console et utilisez npm pour installer la bibliothèque HTTP axios et le package uuid :
npm install axios uuid
Créez le fichier index.js dans le répertoire de l’application.
Conseil
Vous pouvez créer un nouveau fichier à l’aide de PowerShell.
Ouvrez une fenêtre PowerShell dans le répertoire de votre projet en maintenant la touche Maj enfoncée et en cliquant avec le bouton droit sur le dossier.
Tapez la commande New-Item index.js.
Vous pouvez également créer un fichier nommé index.js dans votre IDE et l’enregistrer dans le répertoire translator-text-app.
Copiez et collez les exemples de code dans votre fichier index.js. Veillez à mettre à jour la variable de clé avec la valeur de votre instance Translator du Portail Azure.
Une fois que vous avez ajouté l’exemple de code à votre application, exécutez votre programme :
Accédez à votre répertoire d’application (translator-text-app).
Tapez la commande suivante dans votre terminal :
node index.js
Si vous ne l’avez pas dans votre environnement de développement, installez la dernière version de Python 3.x. Le package d’installation Python (pip) est inclus dans l’installation de Python.
Ouvrez une fenêtre de terminal et utilisez pip pour installer la bibliothèque Requests et le package uuid0 :
pip install requests uuid
Notes
Nous allons également utiliser un package intégré Python appelé json. Il est utilisé pour utiliser des données JSON.
Créez une application Python nommée text-translator.py dans votre éditeur ou IDE favori.
Ajoutez l’exemple code suivant à votre fichier text-translator.py. Veillez à mettre à jour la clé avec l’une des valeurs de votre instance Translator du Portail Azure.
Une fois que vous ajoutez un exemple de code à votre application, générez et exécutez votre programme :
Accédez à votre fichier text-translator.py.
Tapez la commande suivante dans votre console :
python text-translator.py
Important
Les exemples de ce guide nécessitent des clés et des points de terminaison codés en dur.
N’oubliez pas de supprimer la clé de votre code une fois que vous avez terminé, et ne la postez jamais publiquement.
Pour la production, envisagez d’utiliser une méthode de stockage et d’accès sécurisée pour vos informations d’identification. Pour plus d'informations, consultezsécurité Azure AI services.
Traduire le texte
Traduire du texte est l’opération fondamentale du service Translator. Dans cette section, vous générez une requête qui prend une source unique (from) et fournit deux sorties (to). Ensuite, nous examinons quelques paramètres que vous pouvez utiliser pour ajuster à la fois la requête et la réponse.
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=(',', ': ')))
Quand l’appel aboutit, vous devez voir la réponse suivante :
[
{
"translations":[
{
"text":"Halo, rafiki! Ulifanya nini leo?",
"to":"sw"
},
{
"text":"Ciao, amico! Cosa hai fatto oggi?",
"to":"it"
}
]
}
]
Si vous avez besoin d’une traduction, mais que vous ne connaissez pas la langue du texte, vous pouvez utiliser l’opération de détection de la langue. Il existe plusieurs façons d’identifier la langue du texte source. Dans cette section, vous apprenez à utiliser la détection de la langue en utilisant le point de terminaison translate et le point de terminaison detect.
Détecter la langue source pendant la traduction
Si vous n’incluez pas le paramètre from dans votre requête de traduction, le service Translator essaie de détecter la langue du texte source. Dans la réponse, vous obtenez la langue détectée (language) et un score de confiance (score). Plus le score est proche de 1.0, plus la confiance est grande dans la fiabilité de la détection.
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=(',', ': ')))
Quand l’appel aboutit, vous devez voir la réponse suivante :
[
{
"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"
}
]
}
]
Détecter la langue source sans traduction
Il est possible d’utiliser le service Translator pour détecter la langue du texte source sans effectuer de traduction. Pour cela, vous utilisez le point de terminaison /detect.
using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static readonly string location = "<YOUR-RESOURCE-LOCATION>";
static async Task Main(string[] args)
{
// Just detect language
string route = "/detect?api-version=3.0";
string textToLangDetect = "Hallo Freund! Was hast du heute gemacht?";
object[] body = new object[] { new { Text = textToLangDetect } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// Send the request and get response.
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
// Read response as a string.
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
}
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=(',', ': ')))
La réponse du point de terminaison /detect inclut d’autres détections et indique si la traduction et la translittération sont prises en charge pour toutes les langues détectées. Quand l’appel aboutit, vous devez voir la réponse suivante :
La translittération est le processus de conversion d’un mot ou d’une expression depuis l’écriture (l’alphabet) d’une langue vers une autre en fonction de similarités phonétiques. Par exemple, vous pouvez utiliser la translittération pour convertir « สวัสดี » (thai) en « sawatdi » (latn). Il existe plusieurs façons d’effectuer une translittération. Dans cette section, vous apprenez à utiliser la détection de la langue en utilisant le point de terminaison translate et le point de terminaison transliterate.
Translittérer pendant la traduction
Si vous traduisez dans une langue qui utilise un autre alphabet (ou d’autres phonèmes) que votre source, une translittération peut s’avérer nécessaire. Dans cet exemple, nous traduisons « Hello » de l’anglais au thaï. En plus d’obtenir la traduction en thaï, vous obtenez une translittération du mot traduit à l’aide de l’alphabet latin.
Pour obtenir une translittération à partir du point de terminaison translate, utilisez le paramètre toScript.
Notes
Pour obtenir la liste complète des langues et options de translittération disponibles, consultez Langues prises en charge.
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=(',', ': ')))
Quand l’appel aboutit, vous devez voir la réponse suivante. N’oubliez pas que la réponse du point de terminaison translate comprend la langue source détectée avec un score de confiance, une traduction qui utilise l’alphabet de la langue de sortie et une translittération à l’aide de l’alphabet latin.
Vous pouvez également utiliser le point de terminaison transliterate pour obtenir une translittération. Quand vous utilisez le point de terminaison de translittération, vous devez fournir la langue source (language), l’écriture/alphabet source (fromScript) et l’écriture/alphabet de sortie (toScript) en tant que paramètres. Dans cet exemple, nous allons obtenir la translittération de สวัสดีเพื่อน! วันนี้คุณทำอะไร.
Notes
Pour obtenir la liste complète des langues et options de translittération disponibles, consultez Langues prises en charge.
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=(',', ': ')))
Quand l’appel aboutit, vous devez voir la réponse suivante. Contrairement à l’appel au point de terminaison translate, transliterate retourne uniquement le text et la sortie script.
Avec le service Translator, vous pouvez obtenir le nombre de caractères dans une phrase ou une série de phrases. La réponse est retournée sous la forme d’un tableau, avec le nombre de caractères dans chaque phrase détectée. Vous pouvez obtenir les longueurs de phrase avec les points de terminaison translate et breaksentence .
Obtenir la longueur de phrase pendant la traduction
Vous pouvez obtenir le nombre de caractères dans le texte source et dans la sortie traduite à l’aide du point de terminaison translate. Pour retourner la longueur de phrase (srcSenLen et transSenLen), vous devez définir le paramètre includeSentenceLength sur 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=(',', ': ')))
Quand l’appel aboutit, vous devez voir la réponse suivante. En plus de la langue source détectée et de la traduction, vous obtenez le nombre de caractères dans chaque phrase détectée pour la source (srcSentLen) et la traduction (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=(',', ': ')))
Quand l’appel aboutit, vous devez voir la réponse suivante. Contrairement à l’appel au point de terminaison translate, breaksentence retourne uniquement le nombre de caractères dans le texte source dans un tableau appelé sentLen.
Recherche dans le dictionnaire (autres traductions)
Avec le point de terminaison, vous pouvez obtenir d’autres traductions d’un mot ou d’une expression. Par exemple, lors de la traduction du mot « sunshine » de en vers es, ce point de terminaison retourne « luz solar », « rayos solares », « soleamiento », « sol » et « 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=(',', ': ')))
Quand l’appel aboutit, vous devez voir la réponse suivante. Examinons la réponse plus étroitement car le code JSON est plus complexe que certains des autres exemples cités dans cet article. Le tableau translations comprend la liste des traductions. Chaque objet de ce tableau comprend un score de confiance (confidence), le texte optimisé pour l’affichage à l’utilisateur final (displayTarget), le texte normalisé (normalizedText), la nature grammaticale (posTag) et des informations sur la traduction précédente (backTranslations). Pour plus d’informations sur la réponse, consultez Recherche dans le dictionnaire.
Exemples du dictionnaire (traductions en contexte)
Une fois que vous effectuez une recherche dans le dictionnaire, passez le texte source et le texte de traduction au point de terminaison dictionary/examples pour obtenir une liste d’exemples qui montrent les deux termes dans le contexte d’une phrase ou d’une expression. En reprenant l’exemple précédent, vous utilisez les valeurs normalizedText et normalizedTarget données dans la réponse de la recherche dans le dictionnaire en tant que text et translation respectivement. Les paramètres de langue source (from) et de cible de sortie (to) sont obligatoires.
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=(',', ': ')))
Quand l’appel aboutit, vous devez voir la réponse suivante. Pour plus d’informations sur la réponse, consultez Recherche dans le dictionnaire.
[
{
"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."
}
]
}
]
Dépannage
Codes d'état HTTP courants
Code d'état HTTP
Description
Raison possible
200
OK
La demande a abouti.
400
Demande incorrecte
Un paramètre obligatoire est manquant, vide ou présente une valeur Null. Il est également possible que la valeur transmise à un paramètre obligatoire ou facultatif ne soit pas valide. Ce problème est généralement dû à un en-tête trop long.
401
Non autorisé
La requête n’est pas autorisée. Vérifiez que votre clé ou votre jeton est valide et dans la région appropriée. Voir aussiAuthentification.
429
Trop de demandes
Vous avez dépassé le quota ou le taux de requêtes autorisé pour votre abonnement.
502
Passerelle incorrecte
Problème de réseau ou côté serveur. Cette erreur peut également signaler des en-têtes non valides.
Utilisateurs de Java
Si vous rencontrez des problèmes de connexion, il est possible que votre certificat TLS/SSL ait expiré. Pour résoudre ce problème, installez DigiCertGlobalRootG2.crt dans votre magasin privé.