CSharp使用百度翻译

注意事项

需要申请百度翻译 AppID 与Key

通用翻译API 标准版 可以白嫖成为 高级版

说明:对于标准版服务,您的QPS(每秒请求量)=1,如需更大频率,请先进行身份认证,认证通过后可切换为高级版(适用于个人,QPS=10)或尊享版(适用于企业,QPS=100)每月翻译字符数低于 200 万,享免费服务;

注册/查看: https://fanyi-api.baidu.com/

百度翻译API帮助与支持

个人类库地址

拓展了Unity窗口

namespace Timor.Translate
{
    using System;
    using System.Security.Cryptography;
    using System.Text;
    using System.Net;
    using System.IO;
    using LitJson;
    using UnityEngine;

    /// <summary>
    /// 百度翻译
    /// </summary>
    public class BaiDuTranslate
    {
        private string EncryptString(string str)
        {
            MD5 md5 = MD5.Create();
            // 将字符串转换成字节数组
            byte[] byteOld = Encoding.UTF8.GetBytes(str);
            // 调用加密方法
            byte[] byteNew = md5.ComputeHash(byteOld);
            // 将加密结果转换为字符串
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteNew)
            {
                // 将字节转换成16进制表示的字符串,
                sb.Append(b.ToString("x2"));
            }
            // 返回加密的字符串
            return sb.ToString();
        }

        /// <summary>
        /// AppID
        /// </summary>
        public string appID;

        /// <summary>
        /// 密钥
        /// </summary>
        public string secretkey;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="appID">appID</param>
        /// <param name="secretkey">secretkey</param>
        public BaiDuTranslate(string appID, string secretkey)
        {
            this.appID = appID;
            this.secretkey = secretkey;
        }

        /// <summary>
        /// 翻译
        /// </summary>
        /// <param name="q">原文</param>
        /// <param name="from">原语言</param>
        /// <param name="to">目标语言</param>
        /// <returns>返回翻译结果</returns>
        public string Translate(string q, LanguageType from, LanguageType to)
        {
            System.Random rd = new System.Random();
            string salt = rd.Next(100000).ToString();

            string sign = EncryptString(appID + q + salt + secretkey);
            string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            url += "q=" + q;
            //url += "q=" + HttpUtility.UrlEncode(q);
            url += "&from=" + from.ToString();
            url += "&to=" + to.ToString();
            url += "&appid=" + appID;
            url += "&salt=" + salt;
            url += "&sign=" + sign;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = 6000;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            TransObj obj = JsonMapper.ToObject<TransObj>(retString);
            if (obj == null || obj.trans_result == null || (obj.trans_result.Count <= 0))
            {
                Debug.LogWarning("翻译失败了:" + q);
                return q;
            }

            return obj.trans_result[0].dst;
        }
    }
}

 

 

namespace Timor.Translate
{
    /// <summary>
    /// 语言类型
    /// </summary>
    public enum LanguageType
    {
        /// <summary>
        /// 自动检测
        /// </summary>
        auto,

        /// <summary>
        /// 中文
        /// </summary>
        zh,

        /// <summary>
        /// 英语
        /// </summary>
        en,

        /// <summary>
        /// 粤语
        /// </summary>
        yue,

        /// <summary>
        /// 文言文
        /// </summary>
        wyw,

        /// <summary>
        /// 日语
        /// </summary>
        jp,

        /// <summary>
        /// 韩语
        /// </summary>
        kor,

        /// <summary>
        /// 法语
        /// </summary>
        fra,

        /// <summary>
        /// 西班牙语
        /// </summary>
        spa,

        /// <summary>
        /// 泰语
        /// </summary>
        th,

        /// <summary>
        /// 阿拉伯语
        /// </summary>
        ara,

        /// <summary>
        /// 俄语
        /// </summary>
        ru,

        /// <summary>
        /// 葡萄牙语
        /// </summary>
        pt,

        /// <summary>
        /// 德语
        /// </summary>
        de,

        /// <summary>
        /// 意大利语
        /// </summary>
        it,

        /// <summary>
        /// 希腊语
        /// </summary>
        el,

        /// <summary>
        /// 荷兰语
        /// </summary>
        nl,

        /// <summary>
        /// 波兰语
        /// </summary>
        pl,

        /// <summary>
        /// 保加利亚语
        /// </summary>
        bul,

        /// <summary>
        /// 爱沙尼亚语
        /// </summary>
        est,

        /// <summary>
        /// 丹麦语
        /// </summary>
        dan,

        /// <summary>
        /// 芬兰语
        /// </summary>
        fin,

        /// <summary>
        /// 捷克语
        /// </summary>
        cs,

        /// <summary>
        /// 罗马尼亚语
        /// </summary>
        rom,

        /// <summary>
        /// 斯洛文尼亚语
        /// </summary>
        slo,

        /// <summary>
        /// 瑞典语
        /// </summary>
        swe,

        /// <summary>
        /// 匈牙利语
        /// </summary>
        hu,

        /// <summary>
        /// 简体中文
        /// </summary>
        cht,

        /// <summary>
        /// 越南语
        /// </summary>
        vie
    }
}
using System;
using System.Collections.Generic;

[Serializable]
public class TransObj
{
    /// <summary>
    /// 原语言
    /// </summary>
    public string from;

    /// <summary>
    /// 目标语言
    /// </summary>
    public string to;

    /// <summary>
    /// 翻译结果
    /// </summary>
    public List<TransResult> trans_result;
}
using System;

/// <summary>
/// 翻译结果
/// </summary>
[Serializable]
public class TransResult
{
    /// <summary>
    /// 原文
    /// </summary>
    public string src;
    /// <summary>
    /// 译文
    /// </summary>
    public string dst;
}

 

using System;
using UnityEngine;
using UnityEditor;
using Timor.Translate;
using System.Linq;

/// <summary>
/// 翻译窗口
/// </summary>
public class TranslateWindow : EditorWindow
{
    private string from;
    private string to;

    private LanguageType lFrom = LanguageType.en;
    private LanguageType lTo = LanguageType.zh;

    private string appID;
    private string secretkey;

    private BaiDuTranslate baiDu;

    private Vector2 scrollViewValue;

    public void Awake()
    {
        appID = EditorPrefs.GetString("appID");
        secretkey = EditorPrefs.GetString("secretkey");
    }

    public void OnDestroy()
    {
        EditorPrefs.SetString("appID", appID);
        EditorPrefs.SetString("secretkey", secretkey);
    }

    [MenuItem("Tools/Timor/Window/翻译")]
    public static void ShowMenu()
    {
        ShowWindow();
    }

    public static void ShowWindow()
    {
        TranslateWindow WINDOW = GetWindow<TranslateWindow>(false);
        WINDOW.titleContent = new GUIContent("百度翻译", "自定义的翻译窗口");
        WINDOW.position = new Rect(Screen.width / 4, Screen.height / 4, 500f, 500f);
        WINDOW.Show();
    }

    public void OnGUI()
    {
        scrollViewValue = EditorGUILayout.BeginScrollView(scrollViewValue);
        {
            GUILayout.BeginVertical("Box");
            {
                GUILayout.Label("百度翻译");
                appID = EditorGUILayout.PasswordField("appID:", appID);
                secretkey = EditorGUILayout.PasswordField("secretkey:", secretkey);

                if (string.IsNullOrEmpty(appID) || string.IsNullOrEmpty(secretkey))
                {
                    EditorGUILayout.HelpBox("必须输入ID Key,点击下方按钮查询或注册", MessageType.Error);
                    if (GUILayout.Button("百度翻译开发平台"))
                    {
                        Application.OpenURL("https://fanyi-api.baidu.com/");
                    }
                }

                lFrom = (LanguageType)EditorGUILayout.EnumPopup("原文", lFrom);

                GUILayout.Label("↓");

                lTo = (LanguageType)EditorGUILayout.EnumPopup("目标", lTo);
                if(lTo == LanguageType.auto)
                {
                   EditorGUILayout.HelpBox("目标语言不能设置未自动!!!",MessageType.Error);
                }

                GUILayout.Label("输入原文:");
                from = EditorGUILayout.TextArea(from, GUILayout.Height(100f));

                GUILayout.Label("翻译结果:");
                to = EditorGUILayout.TextArea(to, GUILayout.Height(100f));


                if (GUILayout.Button("翻译", GUILayout.Height(50)))
                {
                    if (string.IsNullOrEmpty(appID) || string.IsNullOrEmpty(secretkey))
                    {
                        Debug.LogError("必须输入ID 和 Key");

                    }
                    else if (string.IsNullOrEmpty(from))
                    {
                        Debug.LogError("必须输入原文");
                    }
                    else
                    {
                        baiDu = new BaiDuTranslate(appID, secretkey);
                        string json = baiDu.Translate(from, lFrom, lTo);
                        TransObj t = JsonUtility.FromJson<TransObj>(json);
                        to = t.trans_result.First().dst;
                        Debug.Log(to);
                    }
                }
            }
            GUILayout.EndVertical();
        }
        EditorGUILayout.EndScrollView();
    }
}

 

 

点赞
  1. Barrett说道:
    Internet Explorer Windows XP

    Do you know each other? http://theformationquest.org/pontoon-online-game.htm pontoon casino game Berget’s drive was blocked by Jasmin Handanovic but the goalkeeper was not well screened by his defenders and McGregor pounced to rifle home from close range.

  2. Milan说道:
    Internet Explorer Windows XP

    Incorrect PIN http://www.kopekoteli.com.tr/achilles-slot-machine achilles slot game That’s a lesson Manning learned well during his first four NFL seasons, when his flashes of greatness were often bookended by spectacular failures

  3. Eric说道:
    Internet Explorer Windows XP

    Yes, I play the guitar http://plateroytu.com/how-many-slots-on-roulette-wheel american roulette free game Trading volume is expected to be light this week due to theChristmas holiday, which could increase volatility

  4. Lesley说道:
    Internet Explorer Windows XP

    Sorry, I'm busy at the moment http://voyagermagazine.com.au/realm-of-riches-slot-gams/ realm of riches slot machine Basino said while the rescue was a lengthy process that manatees are able to survive out of water for extended periods of time

  5. Gabriella说道:
    Internet Explorer Windows XP

    This is the job description http://www.dogaltedavi.org/texas-hold-em-bonus.html bonus poker 200 What else would you call six to eight hours practice a day? Meeting the students at the classical dance boarding school “Académie Princesse Grce” was a breathtaking experience

  6. Google Chrome Windows 10

    I simply needed to thank you so much once again. I am not sure the things that I would've implemented without the type of secrets provided by you on such a question. It previously was a very frustrating issue in my opinion, however , observing the very specialised strategy you processed that made me to leap over gladness. I am just happy for this information and in addition hope that you know what a great job you are always getting into teaching people thru your web page. More than likely you have never got to know any of us.

  7. johnanz说道:
    Internet Explorer Windows XP

    aU9sVl http://waldorfdollshop.us/ waldorf doll

  8. AnjelaHit说道:
    Google Chrome Windows 10

    купить электронные сигареты в красном десанте [url=https://hqd.wiki/kupit-hqd-optom/]где закупать hqd оптом[/url]
    ------
    электронная сигарета в солослове [url=https://hqd.wiki/kupit-hqd-optom/]купить hqd оптом в ростове на дону[/url]

  9. gsusnppfrs说道:
    Internet Explorer Windows XP

    9gg49a qgqypdbgdjkj, [url=http://ikfrnzsddspk.com/]ikfrnzsddspk[/url], [link=http://kshqxtzucgdt.com/]kshqxtzucgdt[/link], http://tujokhnfrgtb.com/

  10. Google Chrome Windows 10

    cialis 10 mg

1 505 506 507

发表评论

昵称和uid可以选填一个,填邮箱必填(留言回复后将会发邮件给你)
tips:输入uid可以快速获得你的昵称和头像

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

Title - Artist
0:00