当前位置: 代码迷 >> C# >> csharp:百度通译
  详细解决方案

csharp:百度通译

热度:422   发布时间:2016-04-28 08:30:11.0
csharp:百度翻译

 

参考:http://api.fanyi.baidu.com/api/trans/product/index

http://developer.baidu.com/wiki/index.php?title=%E5%B8%AE%E5%8A%A9%E6%96%87%E6%A1%A3%E9%A6%96%E9%A1%B5/%E7%99%BE%E5%BA%A6%E7%BF%BB%E8%AF%91API

winform:

    /// <summary>    /// 涂聚文    /// </summary>    public partial class Form5 : Form    {        TranClass tranClass = new TranClass();        string url = "";        string youAPI_Id = "geovindu";        /// <summary>        ///         /// </summary>        /// <returns></returns>        DataTable setLanguage()        {            DataTable dt = new DataTable();            dt.Columns.Add("id", typeof(int));            dt.Columns.Add("name", typeof(string));            dt.Rows.Add(1, "中文--英文");            dt.Rows.Add(2, "英文--中文");            dt.Rows.Add(3, "中文--日文");            dt.Rows.Add(4, "日文--中文");            dt.Rows.Add(5, "中文--韩文");            dt.Rows.Add(6, "韩文--中文");            dt.Rows.Add(7, "西班牙文--中文");            dt.Rows.Add(8, "中文--西班牙文");            return dt;        }        /// <summary>        ///         /// </summary>        public Form5()        {            InitializeComponent();        }        /// <summary>        ///         /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void Form5_Load(object sender, EventArgs e)        {            this.cbxTranslateChange.DataSource = setLanguage();            this.cbxTranslateChange.ValueMember = "id";            this.cbxTranslateChange.DisplayMember = "name";        }        /// <summary>        /// 翻译        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void button1_Click(object sender, EventArgs e)        {            WebClient client = new WebClient();  //引用System.Net            string fromTranslate = tbxFromContent.Text; //翻译前的内容            if (!string.IsNullOrEmpty(fromTranslate))            {                //client_id为自己的api_id,q为翻译对象,from为翻译语言,to为翻译后语言                string url = string.Format("http://openapi.baidu.com/public/2.0/bmt/translate?client_id={0}&q={1}&from={2}&to={3}", youAPI_Id, fromTranslate, tranClass.From, tranClass.To);                var buffer = client.DownloadData(url);                string result = Encoding.UTF8.GetString(buffer);                StringReader sr = new StringReader(result);                JsonTextReader jsonReader = new JsonTextReader(sr); //引用Newtonsoft.Json 自带                JsonSerializer serializer = new JsonSerializer();                var r = serializer.Deserialize<TranClass>(jsonReader); //因为获取后的为json对象 ,实行转换                tbxToContent.Text = r.Trans_result[0].dst;  //dst为翻译后的值            }        }        /// <summary>        ///         /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void cbxTranslateChange_SelectedIndexChanged(object sender, EventArgs e)        {            ComboBox comboBox = sender as ComboBox;            switch (comboBox.SelectedIndex)            {                case 1:                    tranClass.From = "zh";                    tranClass.To = "en";                    break;                case 2:                    tranClass.From = "en";                    tranClass.To = "zh";                    break;                case 3:                    tranClass.From = "zh";                    tranClass.To = "jp";                    break;                case 4:                    tranClass.From = "jp";                    tranClass.To = "zh";                    break;                case 5:                    tranClass.From = "zh";                    tranClass.To = "kor";                    break;                case 6:                    tranClass.From = "kor";                    tranClass.To = "zh";                    break;                case 7:                    tranClass.From = "zh";                    tranClass.To = "spa";                    break;                case 8:                    tranClass.From = "spa";                    tranClass.To = "zh";                    break;                default:                    tranClass.From = "auto";                    tranClass.To = "auto";                    break;            }        }    }    public class TranClass    {        public string From { get; set; }        public string To { get; set; }        public List<Trans_result> Trans_result { get; set; }    }    public class Trans_result    {        public string src { get; set; }        public string dst { get; set; }    }    /*          语言简写	名称auto	自动检测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	繁体中文     */}

  

 

webform:

 TranClass tranClass = new TranClass();        string url = "www.dusystem.com";        string youAPI_Id = "geovindu";        /// <summary>        /// 涂聚文        /// </summary>        /// <returns></returns>        DataTable setLanguage()        {            DataTable dt = new DataTable();            dt.Columns.Add("id", typeof(int));            dt.Columns.Add("name", typeof(string));            dt.Rows.Add(1, "中文--英文");            dt.Rows.Add(2, "英文--中文");            dt.Rows.Add(3, "中文--日文");            dt.Rows.Add(4, "日文--中文");            dt.Rows.Add(5, "中文--韩文");            dt.Rows.Add(6, "韩文--中文");            dt.Rows.Add(7, "西班牙文--中文");            dt.Rows.Add(8, "中文--西班牙文");            return dt;        }        /// <summary>        ///         /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                this.DropDownList1.DataSource = setLanguage();                this.DropDownList1.DataTextField = "name";                this.DropDownList1.DataValueField = "id";                this.DropDownList1.DataBind();                //DropDownList1.SelectedIndex = 0;            }        }        /// <summary>        ///         /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        protected void Button1_Click(object sender, EventArgs e)        {            int k = int.Parse(DropDownList1.SelectedValue);            switch (k)            {                case 1:                    tranClass.From = "zh";                    tranClass.To = "en";                    break;                case 2:                    tranClass.From = "en";                    tranClass.To = "zh";                    break;                case 3:                    tranClass.From = "zh";                    tranClass.To = "jp";                    break;                case 4:                    tranClass.From = "jp";                    tranClass.To = "zh";                    break;                case 5:                    tranClass.From = "zh";                    tranClass.To = "kor";                    break;                case 6:                    tranClass.From = "kor";                    tranClass.To = "zh";                    break;                case 7:                    tranClass.From = "zh";                    tranClass.To = "spa";                    break;                case 8:                    tranClass.From = "spa";                    tranClass.To = "zh";                    break;                default:                    tranClass.From = "auto";                    tranClass.To = "auto";                    break;            }            WebClient client = new WebClient();  //引用System.Net            string fromTranslate = this.TextBox1.Text; //翻译前的内容            if (object.Equals(tranClass, null))            {                tranClass.From = "zh";                tranClass.To = "en";            }            if (!string.IsNullOrEmpty(fromTranslate))            {                //client_id为自己的api_id,q为翻译对象,from为翻译语言,to为翻译后语言                string url = string.Format("http://openapi.baidu.com/public/2.0/bmt/translate?client_id={0}&q={1}&from={2}&to={3}", youAPI_Id, fromTranslate, tranClass.From, tranClass.To);                var buffer = client.DownloadData(url);                string result = Encoding.UTF8.GetString(buffer);                StringReader sr = new StringReader(result);                JsonTextReader jsonReader = new JsonTextReader(sr); //引用Newtonsoft.Json 自带                while (jsonReader.Read())                {                    //Response.Write(jsonReader.Value.ToString() + "<br/>");//jsonReader.TokenType.ToString() + "" + jsonReader.ValueType.ToString() + "" +                 }                Response.Write(CallInterface(fromTranslate, tranClass.From, tranClass.To));                var j = JsonConvert.DeserializeObject<TranClass>(result);                //JsonSerializer serializer = new JsonSerializer();                //TranClass p1 = (TranClass)serializer.Deserialize(new JsonTextReader(sr), typeof(TranClass));                //TranClass r = serializer.Deserialize<TranClass>(jsonReader); //因为获取后的为json对象 ,实行转换  反序列化 错误                //this.TextBox2.Text = r.Trans_result[0].dst;  //dst为翻译后的值                if (!object.Equals(j, null))                {                    this.TextBox2.Text = j.Trans_result[0].dst;                }            }        }                /// <summary>        ///         /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)        {                        switch (DropDownList1.SelectedIndex)            {                case 0:                    tranClass.From = "zh";                    tranClass.To = "en";                    break;                case 1:                    tranClass.From = "en";                    tranClass.To = "zh";                    break;                case 2:                    tranClass.From = "zh";                    tranClass.To = "jp";                    break;                case 3:                    tranClass.From = "jp";                    tranClass.To = "zh";                    break;                case 4:                    tranClass.From = "zh";                    tranClass.To = "kor";                    break;                case 5:                    tranClass.From = "kor";                    tranClass.To = "zh";                    break;                case 6:                    tranClass.From = "zh";                    tranClass.To = "spa";                    break;                case 7:                    tranClass.From = "spa";                    tranClass.To = "zh";                    break;                default:                    tranClass.From = "auto";                    tranClass.To = "auto";                    break;            }        }        /// <summary>        /// 请求百度接口        ///         /// https://github.com/lbv/litjson        /// </summary>        /// <param name="sub">要翻译的文本</param>        /// <param name="from">from语言</param>        /// <param name="to">翻译为语言</param>        /// <returns></returns>        private string CallInterface(string sub, string from, string to)        {            HttpContext.Current.Application.Lock();            if (HttpContext.Current.Application["baidu"] == null)            {                HttpContext.Current.Application["baidu"] = 1;            }            else            {                HttpContext.Current.Application["baidu"] = (int)HttpContext.Current.Application["baidu"] + 1;            }            HttpContext.Current.Application.UnLock();            string url = string.Format("http://openapi.baidu.com/public/2.0/bmt/translate?client_id={0}&q={1}&from={2}&to={3}", youAPI_Id, sub, from, to);            string down = "", result = "";            try            {                WebClient wc = new WebClient();                down = wc.DownloadString(url);            }            catch (Exception)            {            }            JsonData jd = JsonMapper.ToObject(down);            if (JsonDataContainsKey(jd, "error_code"))            {                result += sub;            }            else            {                JsonData jdResult = jd["trans_result"];                for (int j = 0; j < jdResult.Count; j++)                {                    JsonData jdDst = jdResult[j]["dst"];                    result += jdDst.ToString();                }            }            return result;        }        /// <summary>        ///         /// </summary>        /// <param name="data"></param>        /// <param name="key"></param>        /// <returns></returns>        public bool JsonDataContainsKey(JsonData data, string key)        {            bool result = false;            if (data == null)                return result;            if (!data.IsObject)            {                return result;            }            IDictionary tdictionary = data as IDictionary;            if (tdictionary == null)                return result;            if (tdictionary.Contains(key))            {                result = true;            }            return result;        }    }    /// <summary>    ///     /// </summary>    public class TranClass    {        public string From { get; set; }        public string To { get; set; }        public List<Trans_result> Trans_result { get; set; }    }    /// <summary>    ///     /// </summary>    public class Trans_result    {        /// <summary>        /// 原文        /// </summary>        public string src { get; set; }        /// <summary>        /// 翻译后的值        /// </summary>        public string dst { get; set; }    }    /*     {"from":"zh","to":"en","trans_result":[{"src":"\u4e2d\u56fd","dst":"China"}]}     */}