csharp:百度翻譯

weixin_33860553發表於2019-01-13

 

參考: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"}]}
     */
}

  

相關文章