一段英文通过百度翻译api在.net4.0框架上如何正常翻译成中文,

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/12 00:09:29
一段英文通过百度翻译api在.net4.0框架上如何正常翻译成中文,

一段英文通过百度翻译api在.net4.0框架上如何正常翻译成中文,
一段英文通过百度翻译api在.net4.0框架上如何正常翻译成中文,

一段英文通过百度翻译api在.net4.0框架上如何正常翻译成中文,
申请个百度开发者帐号
在开发者服务管理里面创建一个工程

学习API文档
编码
/// <summary>
        /// 百度翻译
        /// </summary>
        /// <param name="client_id">应用API(API KEY)</param>
        /// <param name="text">需要反应的文本</param>
        /// <param name="from">源语言</param>
        /// <param name="to">目标语言</param>
        /// <returns>翻译文本</returns>
        private string BaiduTans_Get(string client_id, string text, string from, string to)
        {
            string url = string.Format("
{0}&q={1}&from={2}&to={3}", client_id, text, from, to); 
            WebClient wc = new WebClient();
            /* result:
             * "{\"from\":\"en\",\"to\":\"zh\",\"trans_result\":[{\"src\":\"We are friends\",\"dst\":\"\\u6211\\u4eec\\u662f\\u670b\\u53cb\"}]}"
             */
            string result = wc.DownloadString(url);

            //正则解析,这里正确的应该用JSON解析,但是这个本人不太了解
            //结果:\\u6211\\u4eec\\u662f\\u670b\\u53cb\
            string pattern="\"dst\":\"(?<text>.)\"}]}";
            Regex regex = new Regex(pattern);
            MatchCollection matches = regex.Matches(result);
            string unicodestring = matches[0].Groups["text"].Value;

            //将unicode转换成汉字
            //结果:我们是朋友
            string zhString = ToGB2312(unicodestring);

            return zhString;
        }Debug.WriteLine(BaiduTans_Get("应用API(API KEY)", "We are friends", "en", "zh"));
输出结果:
我们是朋友.