[英]How to use Microsoft Translator API in Java or Android using Azure
我一直在網上搜索幾個小時,以獲取Android或Microsoft Translator Text API的Java的工作示例,因為它是唯一一個每月提供200萬字符免費翻譯的API。 但無濟於事,因為自2017年3月以來我發現的大多數內容已被棄用,並且現已遷移到蔚藍的認知服務,因此沒有任何效果。 有人知道該怎么做嗎? 我在c#中找到了一個工作代碼,該代碼在控制台中輸出了翻譯,但是由於我不是C#,所以無法將其自己轉換為Java。 TIA。
以下是C#中的工作代碼。
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace AzureSubscriptionKeySample
{
class Program
{
/// Header name used to pass the subscription key to translation service
private const string OcpApimSubscriptionKeyHeader = "Ocp-Apim-Subscription-Key";
/// Url template to make translate call
private const string TranslateUrlTemplate = "http://api.microsofttranslator.com/v2/http.svc/translate?text={0}&from={1}&to={2}&category={3}";
private const string AzureSubscriptionKey = "MyAzureSubscriptionKey"; //Enter here the Key from your Microsoft Translator Text subscription on http://portal.azure.com
static void Main(string[] args)
{
TranslateAsync().Wait();
Console.ReadKey();
}
/// Demonstrates Translate API call using Azure Subscription key authentication.
private static async Task TranslateAsync()
{
try
{
var translateResponse = await TranslateRequest(string.Format(TranslateUrlTemplate, "안녕하세요 친구", "ko", "en", "general"), AzureSubscriptionKey);
var translateResponseContent = await translateResponse.Content.ReadAsStringAsync();
if (translateResponse.IsSuccessStatusCode)
{
Console.WriteLine("Translation result: {0}", translateResponseContent);
}
else
{
Console.Error.WriteLine("Failed to translate. Response: {0}", translateResponseContent);
}
}
catch (Exception ex)
{
Console.Error.WriteLine("Failed to translate. Exception: {0}", ex.Message);
}
}
public static async Task<HttpResponseMessage> TranslateRequest(string url, string azureSubscriptionKey)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add(OcpApimSubscriptionKeyHeader, azureSubscriptionKey);
return await client.GetAsync(url);
}
}
}
}
有關棄用的詳細信息: https : //datamarket.azure.com/dataset/bing/microsofttranslatorspeech
您可以通過REST API
使用Microsoft Translator Text API
REST API
。
請參閱此官方文檔以了解更多詳細信息。
在這里,我提供GetTranslations
請求的代碼段以及Java代碼供您參考。
import org.apache.commons.io.IOUtils;
import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Test1 {
private static String key = "<your translator account key>";
public static void main(String[] args) {
try {
// Get the access token
// The key got from Azure portal, please see https://docs.microsoft.com/en-us/azure/cognitive-services/cognitive-services-apis-create-account
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
IOUtils.write("", authConn.getOutputStream(), "UTF-8");
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
System.out.println(token);
// Using the access token to build the appid for the request url
String appId = URLEncoder.encode("Bearer " + token, "UTF-8");
String text = URLEncoder.encode("Hello", "UTF-8");
String from = "en";
String to = "fr";
String translatorTextApiUrl = String.format("https://api.microsofttranslator.com/v2/http.svc/GetTranslations?appid=%s&text=%s&from=%s&to=%s&maxTranslations=5", appId, text, from, to);
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
translateConn.setRequestMethod("POST");
translateConn.setRequestProperty("Accept", "application/xml");
translateConn.setRequestProperty("Content-Type", "text/xml");
translateConn.setDoOutput(true);
String TranslationOptions = "<TranslateOptions xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">" +
"<Category>general</Category>" +
"<ContentType>text/plain</ContentType>" +
"<IncludeMultipleMTAlternatives>True</IncludeMultipleMTAlternatives>" +
"<ReservedFlags></ReservedFlags>" +
"<State>contact with each other</State>" +
"</TranslateOptions>";
translateConn.setRequestProperty("TranslationOptions", TranslationOptions);
IOUtils.write("", translateConn.getOutputStream(), "UTF-8");
String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
System.out.println(resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
希望對您有幫助。
另外,為了添加到@Jay Gongs答案中,它給出了已翻譯文本的完整輸出,例如等級,匹配度等。我創建了一個修訂版本,該修訂僅顯示已翻譯的實際文本。
關於他上面給出的代碼,代碼下面
的System.out.println(RESP);
刪除或注釋上面的代碼,並在下面添加以下行。
// System.out.println(resp);
String s=resp;
Pattern assign_op=Pattern.compile("(<TranslatedText>)"
+ "|(<\\/TranslatedText>)"
+ "|[()\\\\[\\\\]{};=#.,'\\\\^:@!$%&_`*-<>]"
+ "|[a-zA-Z0-9\\s]*"
+ "");
Matcher m = assign_op.matcher(s) ;
Boolean endOfTransTxt=false,startOfTransTxt=false,concat=false;
String foundRegexStr="",tempStr="";
while (m.find()) {
foundRegexStr=m.group();
if(m.group().matches("(<TranslatedText>)")) {
startOfTransTxt=true;
}
else if(m.group().matches("(<\\/TranslatedText>)")) {
endOfTransTxt=true;
concat=false;
}
else{
startOfTransTxt=false;
endOfTransTxt=false;
}
if(startOfTransTxt==true) {
concat=true;
}
else if(concat==true) {
tempStr=tempStr+""+m.group();
}
else {
}
}
System.out.println("\nTranslated Text: "+tempStr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.