首页 > 代码库 > 利用百度翻译API实现多语言的翻译

利用百度翻译API实现多语言的翻译

支持语言:

中英、英中、中日、日中、中韩、韩中、中法、法中、中西、西中、中泰、泰中、中阿、阿中、中俄、俄中、英日、日英、英泰、泰英、英阿、阿英、英西、西英、英葡、葡英
频率限制:

普通开发者提供1000次/小时限制,支持扩容;
GET请求方式:
http://openapi.baidu.com/public/2.0/bmt/translate?client_id=YourApiKey&q=today&from=auto&to=auto
响应示例:
{"from":"en","to":"zh","trans_result":[{"src":"today","dst":"\u4eca\u5929"}]}
目前支持11种语言,如下所示:
中文  zh  英语  en 
日语  jp  韩语  kor 
西班牙语  spa  法语  fra 
泰语  th  阿拉伯语  ara 
俄罗斯语  ru  葡萄牙语  pt 
粤语  yue  文言文  wyw 
白话文  zh  自动检测  auto 
步骤:
Step1. 申请ApiKey,
http://developer.baidu.com/console#app/project
Step2. 组成Get请求
Step3. 获得响应
Step4. 对响应进行解析(关键)
Step5. 结果输出

关键代码(C#):
public string getTraslation(string src)
        {
            //发送请求
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://openapi.baidu.com/public/2.0/bmt/translate?client_id=" + client_id + "&q=" + src + "&from=" + from + "&to=" + to);

//获得响应
            string res = string.Empty;
            try
            {
                //获取响应流
                HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                res = reader.ReadToEnd();
                reader.Close();
                response.Close();

//正则表达式
                string pattern = @"""dst"":""(?.*?)""}";
                MatchCollection matchs;
                string result = string.Empty;
                matchs = Regex.Matches(res, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                foreach (Match m in matchs)
                {
                    string strTokenValue = http://www.mamicode.com/m.Groups["tokenVal"].Value;
                    string[] stringSeparators = new string[] { "\\u" };
                    string[] unicodeArray = strTokenValue.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
                    StringBuilder sb = new StringBuilder();
                    if (unicodeArray.Length <= 1)
                    {
                        result = strTokenValue;
                    }
                    else
                    {
                        foreach (string item in unicodeArray)
                        {
                            byte[] codes = new byte[2];
                            int code1, code2;
                            code1 = Convert.ToInt32(item.Substring(0, 2), 16);
                            code2 = Convert.ToInt32(item.Substring(2), 16);
                            codes[0] = (byte)code2;//必须是小端在前
                            codes[1] = (byte)code1;
                            sb.Append(Encoding.Unicode.GetString(codes));
                        }
                        result = sb.ToString();
                    }
                }
                return result;
            }
            catch (Exception)
            {
                return null;
            }
        }

关键代码(Java):

public String getResult(String input){
  try {
   String src = http://www.mamicode.com/URLEncoder.encode(input,"utf-8");
   httpGet = new HttpGet("http://openapi.baidu.com/public/2.0/bmt/translate?client_id="+client_id+"&q="+src+"&from="+from+"&to="+to);
   httpResponse = httpClient.execute(httpGet);
   httpEntity = httpResponse.getEntity();
   String content = EntityUtils.toString(httpEntity, "utf-8");
   Matcher matcher = Pattern.compile("\"dst\":\"(?.*?)\"}").matcher(content);
   
   if (matcher.find()){
             strTokenValue = http://www.mamicode.com/matcher.group("tokenVal");
             String[] sarray = strTokenValue.split("\\\\u");
             if (sarray.length <= 1){
              result = strTokenValue;
             }
             else {
              mybyte = new byte[2*sarray.length-2];
              for (int i = 0; i < sarray.length-1; i++){
               mybyte[2*i] = (byte)Integer.parseInt(sarray[i+1].substring(0, 2), 16);
               mybyte[2*i+1] = (byte)Integer.parseInt(sarray[i+1].substring(2, 4), 16);
              }
              result = new String(mybyte,"utf-16");
    }
            }
   httpGet.abort();
   return result;
  } catch (Exception e) {
   return null;
  }
 }


请加微信:xiaoran-668

利用百度翻译API实现多语言的翻译