在线应用-调用百度翻译引擎

百度翻译引擎目前免费开放了,支持27中语言的互译,足够各领域使用了,这对于有语言处理需求的应用来说省掉了不少麻烦,可以专注于专业的方向了。话不多说,如何调用百度翻译引擎呢?下面就是为有达网机器人实现的翻译模块,纯Java实现,百度api使用RESTFUL风格,调用过程简洁。对于想搞微信应用、智能客服或网站建设的小白朋友或许有些帮助(大神忽略^_^)。

package com.tomrrow.baidu;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

/**
* 百度翻译引擎调用
*
*/
public class BaiduTranslate{
    private static final String UTF8 = "utf-8";
    //申请者开发者id,实际使用时请修改成开发者自己的appid
    private static final String appId = "20160619234234";

    //申请成功后的证书token,实际使用时请修改成开发者自己的token
    private static final String token = "rIyTCTesswefewfewf";

    private static final String url = "https://api.fanyi.baidu.com/api/trans/vip/translate";

    //随机数,用于生成md5值,开发者使用时请激活下边第四行代码
    private static final Random random = new Random();
    private static String translate(String q, String from, String to) throws Exception{
        //用于md5加密
        int salt = random.nextInt(10000);
        //本演示使用指定的随机数为1435660288
        //int salt = 1435660288;
        // 对appId+源文+随机数+token计算md5值
        StringBuilder md5String = new StringBuilder();
        md5String.append(appId).append(q).append(salt).append(token);
        String md5 = DigestUtils.md5Hex(md5String.toString());
        md5String = null;

        //使用Post方式,组装参数
        HttpPost httpost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 
        nvps.add(new BasicNameValuePair("q", q)); 
           nvps.add(new BasicNameValuePair("from", from)); 
           nvps.add(new BasicNameValuePair("to", to)); 
           nvps.add(new BasicNameValuePair("appid", appId)); 
           nvps.add(new BasicNameValuePair("salt", String.valueOf(salt))); 
           nvps.add(new BasicNameValuePair("sign", md5)); 
        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); 

        //创建httpclient链接,并执行
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = httpclient.execute(httpost);
        //对于返回实体进行解析
        HttpEntity entity = response.getEntity();
        InputStream returnStream = entity.getContent();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(returnStream, UTF8));
        StringBuilder result = new StringBuilder();
        String str = null;
        while ((str = reader.readLine()) != null) {
            result.append(str).append("\n");
        }
        //转化为json对象,注:Json解析的jar包可选其它
        JSONObject resultJson = new JSONObject(result.toString());

        //开发者自行处理错误,本示例失败返回为null
        String error_code = null;
        try {
            error_code = resultJson.getString("error_code");
            if (error_code != null) {
                //return null;
                throw new RuntimeException("出错代码:" + error_code + " 出错信息:" + resultJson.getString("error_msg"));
            }
        } catch (Exception e) {}
        finally{
            error_code = null;
        }
        //获取返回翻译结果
        JSONArray array = (JSONArray) resultJson.get("trans_result");
        JSONObject dst = (JSONObject) array.get(0);
        String text = dst.getString("dst");
        text = URLDecoder.decode(text, UTF8);
        dst = null;
        array = null;
        return text;
    }
    /**
     * 调用百度翻译服务(将待翻译语料从源语言语种翻译成目标语言语种)
     * @param q 待翻译语料
     * @param from 源语言语种
     * @param to 目标语言语种
     * @return
     * @throws Exception
     */
    public static String  translateToTarget(String q, String from, String to) throws RuntimeException{
        String result = null;
        try {
            result = translate(q, from, to);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }
    /**
     * 调用百度翻译服务(将待翻译语料从源语言语种翻译成目标语言语种)
     * @param q 待翻译语料
     * @param toName 目标语言语种
     * @return
     * @throws Exception
     */
    public static String  translateToTarget(String q, String toName) throws RuntimeException{
        String result = null;
        try {
            result = translate(q, "auto", getTransTagert(toName));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }
    private static String getTransTagert(String toName){
        String[][] lans = {{"zh","中文","汉语","中国话","方块字","国语"},{"en","英语","英文","美语","美式英语"},{"yue","粤语","广东话"},{"wyw","文言文"},{"jp","日语","日本话","日文"},
                {"kor","韩语","韩文","韩国话"},{"fra","法语","法兰西语","法国话","法文"},{"spa","西班牙语"},{"th","泰语","泰国语"},{"ara","阿拉伯语","阿拉伯文"},{"ru","俄语","俄文","俄国话"},
                {"pt","葡萄牙语","葡萄牙文"},{"de","德语","德文"},{"it","意大利语","意大利文"},{"el","希腊语","希腊文"},{"nl","荷兰语","荷兰文"},{"pl","波兰语","波兰文"},
                {"bul","保加利亚语"},{"est","爱沙尼亚语"},{"dan","丹麦语"},{"fin","芬兰语"},{"cs","捷克语"},{"rom","罗马尼亚语"},{"slo","斯洛文尼亚语"},{"swe","瑞典语"},
                {"hu","匈牙利语"},{"cht","繁体中文","繁体汉字"}};
        String temp = "zh";
        for (int x = 0; x < lans.length; x++){
            for (int y = 0; y < lans[x].length; y++){
                if (lans[x][y].indexOf(toName) == 0){
                    temp = lans[x][0];
                    break;
                }
            }
        }
        return temp;
    }

public static void main(String[] args) throws Exception {
        String source = "学而时习之";
        String result = BaiduTranslate.translateToTarget(source, "auto", "en");
        if(result == null){
            System.out.println("翻译出错,参考百度错误代码和说明。");
            return;
        }
        System.out.println(source + ":" + result);
    }

}

声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《在线应用-调用百度翻译引擎
本文地址:http://www.xiupu.net/archives-7484.html
关注公众号:嗅谱网

赞赏

wechat pay微信赞赏alipay pay支付宝赞赏

上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!