问题描述
如果您转到https://www.bing.com/translator(使用MS / Azure转换器api)并输入word
的意思是从英语到瑞典语,除了“主要”翻译外,您还将获得没错,您还有一个包含“其他表达方式”的部分,该部分按动词,名词和形容词分组。
我想知道如何从响应中获取此组列表。
现在我有以下内容,但它仅返回主要翻译,在这种情况下为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,"[{\n\t\"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;
}
解决方法
您可以使用“词典查找”资源检索替代翻译。 https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-dictionary-lookup
它返回posTag属性中的词性。然后,您可以按posTag分组以实现类似的分组。
Dictionary范例资源也返回您在Bing Translator网站上看到的例句。 https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-dictionary-examples