C#使用百度翻译API

API网址:

http://developer.baidu.com/wiki/index.php?title=帮助文档首页/百度翻译/翻译API


核心代码:

   /// <summary>
    /// 请求百度接口
    /// </summary>
    /// <param name="sub">要翻译的文本</param>
    /// <param name="from">from语言</param>
    /// <param name="to">翻译为语言</param>
    /// <returns></returns>
    static 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}", CLIENT_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;
    }

    static 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;
    }

支持的翻译方向:

from字段to字段翻译方向
autoauto自动识别
zhen中 -> 英
zhjp中 -> 日

语种编码

目前支持13种语言,如下所示:

语种代码语种代码
中文zh英语en
日语jp韩语kor
西班牙语spa法语fra
泰语th阿拉伯语ara
俄罗斯语ru葡萄牙语pt
粤语yue文言文wyw
白话文zh自动检测auto
德语de意大利语it

JsonData使用了LitJSON库。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程圈子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值