If you go to https://www.bing.com/translator, (which uses the MS/Azure Translator api) and type in the word
mean from English to Swedish, in addition to the “main” translation you get on the right, you also have a section that has “Other ways to say”, which are grouped by Verb, Noun, and Adjective.
I would like to know how I can fetch this list of groups from the response.
Right now I have the following, but it only returns the main translation, in this case Menar
.
import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Protocol; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; protected String doInBackground(String... params) { String word = params[0]; String translationType = params[1]; MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "[{nt"Text": "" + word + ""n}]"); Request request = new Request.Builder() .url(BASE_URL + translationType) .post(body) .addHeader("Ocp-Apim-Subscription-Key", SUBSCRIPTION_KEY) .addHeader("Ocp-Apim-Subscription-Region", SUBSCRIPTION_REGION) .addHeader("Content-type", "application/json") .build(); Response response = okHttpClient.newCall(request) .execute(); if (!response.isSuccessful()) { throw new AzureTranslateException("Failed to get translations from Azure Translator API, due to: " + response.message()); } String json = response.body().string(); // remove the first and last characters, which are brackets, for ObjectMapper json = json.substring(1, json.length() - 1); // this will only have ONE translation AzureTranslateResponse r = new ObjectMapper().readValue(json, AzureTranslateResponse.class); return r.getTranslations().get(0).getText(); }
AzureTranslatorResponse
@Data public class AzureTranslateResponse { private DetectedLanguage detectedLanguage; private List<Translation> translations; }
DetectedLanguage
@Data public class DetectedLanguage { private String language; private double score; }
DetectedLanguage
@Data public class DetectedLanguage { private String language; private double score; }
Advertisement
Answer
You can retrieve alternative translations using the Dictionary Lookup resource. https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-dictionary-lookup
It returns the part of speech in the posTag attribute. You can then group by posTag to achieve a similar grouping.
The Dictionary Examples resource returns the example sentences that you see on the Bing Translator site as well. https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-dictionary-examples