C# 百度翻译 中译英

原文链接:https://www.cnblogs.com/vaevvaev/p/9037076.html

该博主的代码写的很详细,而且有注释,很容易看懂。可以直接使用。并且还提供了谷歌翻译和有道翻译。但由于我系统需求是翻译文章,里面会有各种样式、符号,直接使用,会影响翻译结果,所以,我稍微改了一点。

首先到百度翻译开放平台申请APPID

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Indonesia.Common.Log;
using System.Security.Cryptography;
using System.Web.Script.Serialization;
using System.Web;

namespace Indonesia.Common.BaiDu
{
    public static class BaiDuTranslate
    {
        /// <summary>
        /// 中文转英文
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string TranslateCnToEn(string text)
        {
            var resultStr = "";
            if (text.Length > 1 * 10000)
            {
                //当字符串过长时,需要截断字符串
                int s = text.Length / 10000;
                int y = text.Length % 10000;
                if (y > 1) s = s + 1;
                int i = 0;

                while (i < s)
                {
                    var q = "";
                    if (i == 0)
                    {
                        q = text.Substring(0, 10000);
                    }
                    else if (i == s - 1)
                    {
                        q = text.Substring((i * 10000) + 1);
                    }
                    else
                    {
                        q = text.Substring((i * 10000) + 1, i * 10000);
                    }
                    resultStr = resultStr + GetTranslationFromBaiduFanyi(q, "zh", "en");
                    i = i + 1;
                }
                return resultStr;
            }
            else
            {
                return GetTranslationFromBaiduFanyi(text, "zh", "en");
            }
        }

        #region 测试通过
        /// <summary>
        /// 调用百度翻译API进行翻译
        /// 详情可参考http://api.fanyi.baidu.com/api/trans/product/apidoc
        /// </summary>
        /// <param name="q">待翻译字符</param>
        /// <param name="from">源语言</param>
        /// <param name="to">目标语言</param>
        /// <returns></returns>
        private static string GetTranslationFromBaiduFanyi(string q, string from, string to)
        {
            string resultStr = "";
            try
            {
                q = q.Replace("\"", "&*&*");//把双引符号替换成指定字符,要不然,翻译的过程中容易丢失符号
                //到百度翻译API的官网申请APPID
                //一定要去申请,不然程序的翻译功能不能使用
                string appId = "appID";
                string password = "秘钥";

                string jsonResult = String.Empty;
                //源语言
                string languageFrom = from.ToLower();
                //目标语言
                string languageTo = to.ToLower();
                //随机数
                string randomNum = System.DateTime.Now.Millisecond.ToString();
                //md5加密
                string md5Sign = GetMD5WithString(appId + q + randomNum + password);
                //url
                string url = String.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}",
                    HttpUtility.UrlEncode(q, Encoding.UTF8),
                    languageFrom,
                    languageTo,
                    appId,
                    randomNum,
                    md5Sign
                    );
                WebClient wc = new WebClient();
                jsonResult = wc.DownloadString(url);
                //解析json
                JavaScriptSerializer jss = new JavaScriptSerializer();
                TranslationResult result = jss.Deserialize<TranslationResult>(jsonResult);
                //判断是否出错
                if (result.Error_code == null)
                {
                    resultStr = result.Trans_result[0].Dst;
                    //文本在翻译的过程中,特殊符号前后有时候会多空格;如&nbsp;可能会翻译为 & nbsp;会导致样式丢失,所以,这个地方处理下
                    resultStr = resultStr.Replace(" *", "*");
                    resultStr = resultStr.Replace("* ", "*");
                    resultStr = resultStr.Replace("& ", "&");
                    resultStr = resultStr.Replace("/ ", "/");
                    resultStr = resultStr.Replace(" /", "/");
                    resultStr = resultStr.Replace(" <", "<");
                    resultStr = resultStr.Replace("< ", "<");
                    resultStr = resultStr.Replace(" >", ">");
                    resultStr = resultStr.Replace("> ", ">");
                    resultStr = resultStr.Replace("&#39;", "");
                    resultStr = resultStr.Replace(". ", ".");
                    resultStr = resultStr.Replace(" .", ".");
                    resultStr = resultStr.Replace("&quot;", "");
                    resultStr = resultStr.Replace("&*&*", "\"");
                }
                else
                {
                    //检查appid和密钥是否正确
                    resultStr="翻译出错,错误码:" + result.Error_code + ",错误信息:" + result.Error_msg;
                }
            }
            catch(Exception ex)
            {
                resultStr = "翻译出错:" + ex.Message;
            }
            return resultStr;
        }
        //对字符串做md5加密
        private static string GetMD5WithString(string input)
        {
            if (input == null)
            {
                return null;
            }
            MD5 md5Hash = MD5.Create();
            //将输入字符串转换为字节数组并计算哈希数据  
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            //创建一个 Stringbuilder 来收集字节并创建字符串  
            StringBuilder sBuilder = new StringBuilder();
            //循环遍历哈希数据的每一个字节并格式化为十六进制字符串  
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            //返回十六进制字符串  
            return sBuilder.ToString();
        }

        public class Translation
        {
            public string Src { get; set; }
            public string Dst { get; set; }
        }
        public class TranslationResult
        {
            //错误码,翻译结果无法正常返回
            public string Error_code { get; set; }
            public string Error_msg { get; set; }
            public string From { get; set; }
            public string To { get; set; }
            public string Query { get; set; }
            //翻译正确,返回的结果
            //这里是数组的原因是百度翻译支持多个单词或多段文本的翻译,在发送的字段q中用换行符(\n)分隔
            public Translation[] Trans_result { get; set; }
        }
        #endregion
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值