zoukankan      html  css  js  c++  java
  • 利用有道翻译实现英汉互译

    以下程序需要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
    预防登革热。最近格林纳达登革热病例显示多个和病毒变异的趋势,增加风险

     有道的翻译质量还是不错的。

  • 相关阅读:
    mysql全文索引
    oracle窗口函数的实战
    数据库的三大范式
    Oracle12cR1 Data Guard 实施文档
    Oracle 11gR2 RAC 删除节点
    Jboss部署文档
    Hexo搭建静态博客踩坑日记(一)
    一行代码引入博客园樱花飘落特效
    Hexo搭建静态博客踩坑日记(二)
    学习axios必知必会(2)~axios基本使用、使用axios前必知细节、axios和实例对象区别、拦截器、取消请求
  • 原文地址:https://www.cnblogs.com/heyang78/p/3447634.html
Copyright © 2011-2022 走看看