利用有道翻译实现英汉互译
生活随笔
收集整理的這篇文章主要介紹了
利用有道翻译实现英汉互译
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
以下程序需要google jason jar的輔助,你可以從 http://pan.baidu.com/s/17qSuq 這里下載。
程序如下:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Main{
public static void main(String[] args) throws Exception{
System.out.println(translate("預防登革熱。最近格林納達登革熱病例顯示多個和病毒變異的趨勢和增加的風險"));
System.out.println(translate("Prevention of dengue fever. Grenada dengue cases show multiple recently and the trend of virus variation and increase the risk"));
}
public static String translate(String text) throws Exception{
final String Youdao_Url = "http://fanyi.youdao.com/openapi.do?keyfrom=sxt102400&key=1695079984&type=data&doctype=json&version=1.1&q=";
StringBuilder YoudaoAPIURL = new StringBuilder();
YoudaoAPIURL.append(Youdao_Url).append(URLEncoder.encode(text, "UTF-8"));
HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(YoudaoAPIURL.toString()).openConnection();
String rawData=stream2string(httpURLConnection.getInputStream());
JsonObject jsonObj = new JsonParser().parse(rawData).getAsJsonObject();
if ("0".equals(jsonObj.get("errorCode").toString()))
{
String finalData = jsonObj.get("translation").getAsString();
return finalData;
}else{
return "Error!";
}
}
/**
* Transform stream to String
* @param is
* @return
*/
private static String stream2string(InputStream is) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringWriter writer = new StringWriter();
char[] buffer = new char[10240];
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
reader.close();
return writer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
控制臺輸出如下:
Prevention of dengue fever. Grenada dengue cases show multiple recently and the trend of virus variation and increase the risk
預防登革熱。最近格林納達登革熱病例顯示多個和病毒變異的趨勢,增加風險
有道的翻譯質量還是不錯的。
總結
以上是生活随笔為你收集整理的利用有道翻译实现英汉互译的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spark启动程序:Master
- 下一篇: 小米最贵量产机来了!小米MIX FOLD