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

  

时间: 2024-10-01 04:19:27

csharp:百度翻译的相关文章

百度翻译APi接口实现

案例使用百度翻译API接口,实现文本翻译 为保证翻译质量,请将单次请求长度控制在 6000 bytes以内.(汉字约为2000个) 签名生成方法如下: 1.将请求参数中的 APPID(appid), 翻译query(q, 注意为UTF-8编码), 随机数(salt), 以及平台分配的密钥(可在管理控制台查看) 按照 appid+q+salt+密钥 的顺序拼接得到字符串1. 2.对字符串1做md5,得到32位小写的sign. 注意: 1.请先将需要翻译的文本转换为UTF-8编码 2.在发送HTTP

学习python:实例1.百度翻译

效果: 代码: # 百度翻译 # Python 3.5.1 from urllib import request, parse import json url = 'http://fanyi.baidu.com/v2transapi' context = input('请输入需要翻译的内容 :\> ') if context >= '\u4e00' and context <= '\u9fa5':     # 判断输入内容是否为汉字     From,To = 'zh','en' els

Thinkphp3.2.3多语言翻译以及使用百度翻译

一.Thinkphp多语言翻译 首先在Common/conf/config.php文件中写入如下内容: <?php return array(     //'配置项'=>'配置值'     //语言包配置     'LANG_SWITCH_ON' => true, // 开启语言包功能     'LANG_AUTO_DETECT' => true, // 自动侦测语言 开启多语言功能后有效     'LANG_LIST' => 'zh-cn,en-us,zh-tw', //必

python学习日记-百度翻译GUI

跟女朋友聊天的时候,女朋友抱怨每次翻译都要打开百度网页上找,这让我有了做一个小的翻译界面的想法,搜索百度翻译居然发现其有API,正合我意,上百度翻译开放平台注册一个个人测试帐号就可以了,东拼西凑,做出了来一个小程序,代码如下: 1 # coding=utf-8 2 from Tkinter import * 3 import tkMessageBox 4 import urllib2 5 import hashlib 6 import json 7 8 9 trans_id = '*******

日常API之百度翻译

百度翻译是什么,可以吃吗?相信很多人都熟悉,它是我们生活中必不可少的一只东东. 但是,百度翻译开发平台只有每月只能翻译200万个字符,多出的要按照49.00/百万字符来算.对于我酱紫的乞丐程序员来说,其实已经是足足的了. 接下来进入正题,分为2个部分讲,一是免费的百度翻译,二是收费的百度翻译(此处应该不会有人看) 首先讲讲免费的吧,这个API呢请求很简单,而且速度快. 一.免费版(无限制,且速度快) 先打开一只Cat,啊不,是翻译和Chrome(只要可以抓包的浏览器都可以,此处用Chrome做示

百度翻译开放接口JAVA实现

百度翻译的开放接口文档在这里:http://api.fanyi.baidu.com/api/trans/product/apidoc 至于申请key啥的就不说了,直接进实现. 我是用HC4.5.1做的,在部分代码处理上面,会跟3 4 的版本有点不一致. public static void main(String[] args) { String query = "搞个乜"; get(query); post(query); } private static void get(Stri

php处理json码 实例:PHP实现百度翻译API调用处理

今天给一个小程序写后台,通过调用百度翻译API实现翻译功能. 调用百度API的url为'http://openapi.baidu.com/public/2.0/translate/dict/simple?client_id=你的KEY&q=要查的汉语&from=zh&to=en'; 申请步骤详见点击打开链接 以上是前期准备工作 ==============================================================================

基于百度翻译API开发属于自己的翻译工具

你是否每天使用着网页翻译工具?你是否遇到过这种情况,上网过程中遇到一个很长的单词但是又不能复制,要开两个浏览器,一个打开百度翻译,照着另一个网页输入单词?你安装了各种翻译软件后,又删除,只因忍受不了那每次弹出来的广告?其实我们想要的就是简单的翻译一个单词.今天就来使用百度翻译开放API,做一个属于自己的翻译工具,只有简单的翻译功能,至于外观自己根据自己的爱好,想做成什么样就做成什么样,终于可以任性一回了~~ 下面先来看一下词典效果:  一.百度翻译API简介 百度翻译可以通过HTTP访问,返回J

百度翻译API

1 #/usr/bin/env python3 2 #coding=utf8 3 4 """百度翻译api功能实现函数,本模块基于Python3.x实现,getTransResult(q)中参数q是需被翻译的内容,目前该函数的源语言默认英文,目标语言默认简体中文""" 5 6 7 import http.client 8 import hashlib 9 import urllib 10 import random 11 import demjs