最新C#调用Google即时翻译

2022-09-29 08:07:55 浏览数 (1)

主要是调用谷歌的翻译API进行翻译,WebRequest的请求,将获取到的翻译提取出来。下面上代码

需要用到一个的js文件:对获取到数据的过滤,命名为gettk.js

代码语言:javascript复制
var b = function(a,b){
    for(var d = 0; d <b.length  -  2; d   = 3){
        var c = b.charAt(d   2),
            c =“a”<= c?c.charCodeAt(0) -  87:数字(c),
            c =“ ”== b.charAt(d   1)?a >>> c:a << c;
        a =“ ”== b.charAt(d)?a   c&4294967295:a ^ c
    }
    返回一个
}

var tk = function(a,TKK){
    for(var e = TKK.split(“。”),h = Number(e [0])|| 0,g = [],d = 0,f = 0; f <a.length; f   ){
        var c = a.charCodeAt(f);
        128> c?g [d   ] = c:(2048> c?g [d   ] = c >> 6 | 192:(55296 ==(c&64512)&& f   1 <a.length && 56320 ==(a.charCodeAt( f   1)&64512)?(c = 65536  ((c&1023)<< 10) (a.charCodeAt(   f)&1023),g [d   ] = c >> 18 | 240,g [d   ] = c >> 12&63 | 128):g [d   ] = c >> 12 | 224,g [d   ] = c >> 6&63 | 128),g [d   ] = c&63 | 128)
    }
    a = h;
    for(d = 0; d <g.length; d   )a   = g [d],a = b(a,“  -a ^   6”);
    a = b(a,“  -3 ^   b   -f”);
    a ^ =数字(e [1])|| 0;
    0> a &&(a =(a&2147483647)  2147483648);
    a%= 1E6;
    返回a.toString() “。”  (a ^ h)
}
    for(var d = 0; d <b.length  -  2; d   = 3){
        var c = b.charAt(d   2),
            c =“a”<= c?c.charCodeAt(0) -  87:数字(c),
            c =“ ”== b.charAt(d   1)?a >>> c:a << c;
        a =“ ”== b.charAt(d)?a   c&4294967295:a ^ c
    }
    返回一个
}

var tk = function(a,TKK){
    for(var e = TKK.split(“。”),h = Number(e [0])|| 0,g = [],d = 0,f = 0; f <a.length; f   ){
        var c = a.charCodeAt(f);
        128> c?g [d   ] = c:(2048> c?g [d   ] = c >> 6 | 192:(55296 ==(c&64512)&& f   1 <a.length && 56320 ==(a.charCodeAt( f   1)&64512)?(c = 65536  ((c&1023)<< 10) (a.charCodeAt(   f)&1023),g [d   ] = c >> 18 | 240,g [d   ] = c >> 12&63 | 128):g [d   ] = c >> 12 | 224,g [d   ] = c >> 6&63 | 128),g [d   ] = c&63 | 128)
    }
    a = h;
    for(d = 0; d <g.length; d   )a   = g [d],a = b(a,“  -a ^   6”);
    a = b(a,“  -3 ^   b   -f”);
    a ^ =数字(e [1])|| 0;
    0> a &&(a =(a&2147483647)  2147483648);
    a%= 1E6;
    返回a.toString() “。”  (a ^ h)
}

前台代码:

代码语言:javascript复制
<Window x:Class =“Translate.MainWindow”
        的xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        的xmlns:X = “http://schemas.microsoft.com/winfx/2006/xaml”
        Title =“Google翻译”高度=“439”宽度=“525”WindowStartupLocation =“CenterScreen”>
    <网格>
        <Grid.Background>
            <ImageBrush ImageSource =“t012abd86418d9b50f9.jpg”/>
        </Grid.Background>
        <TextBlock Height =“23”Horizo​​ntalAlignment =“Left”Margin =“12,12,0,0”FontSize =“14”Name =“textBlock1”Text =“输入单词:”VerticalAlignment =“Top”/>
        <TextBox Foreground =“Red”FontSize =“14”Background =“Transparent”Height =“94”Horizo​​ntalAlignment =“Left”Margin =“10,40,0,0”Name =“txtWord”VerticalAlignment =“Top”Width = “487”TextChanged =“txtWord_TextChanged”/>
        <TextBox Foreground =“Red”FontSize =“14”Background =“Transparent”Height =“242”Horizo​​ntalAlignment =“Left”Margin =“10,157,0,0”Name =“txtResult”VerticalAlignment =“Top”Width =“487 “/>
    </网格>
</窗口>
        的xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        的xmlns:X = “http://schemas.microsoft.com/winfx/2006/xaml”
        Title =“Google翻译”高度=“439”宽度=“525”WindowStartupLocation =“CenterScreen”>
    <网格>
        <Grid.Background>
            <ImageBrush ImageSource =“t012abd86418d9b50f9.jpg”/>
        </Grid.Background>
        <TextBlock Height =“23”Horizo​​ntalAlignment =“Left”Margin =“12,12,0,0”FontSize =“14”Name =“textBlock1”Text =“输入单词:”VerticalAlignment =“Top”/>
        <TextBox Foreground =“Red”FontSize =“14”Background =“Transparent”Height =“94”Horizo​​ntalAlignment =“Left”Margin =“10,40,0,0”Name =“txtWord”VerticalAlignment =“Top”Width = “487”TextChanged =“txtWord_TextChanged”/>
        <TextBox Foreground =“Red”FontSize =“14”Background =“Transparent”Height =“242”Horizo​​ntalAlignment =“Left”Margin =“10,157,0,0”Name =“txtResult”VerticalAlignment =“Top”Width =“487 “/>
    </网格>
</窗口>

后台代码:需要添加MSScriptControl引用,解析Js文件

代码语言:javascript复制
 #region方法

        /// <summary>正则校验
        /// </ summary>
        /// <param name =“str”> </ param>
        /// <param name =“matchStr”>正则</ param>
        /// <returns> </ returns>
        public static bool ValidateStr(string str,string matchStr)
        {
            尝试
            {
                return System.Text.RegularExpressions.Regex.IsMatch(str,matchStr);
            }
            catch(例外)
            {
                返回false;
            }
        }
        /// <summary>
        ///谷歌翻译
        /// </ summary>
        /// <param name =“text”>待翻译文本</ param>
        /// <param name =“fromLanguage”>自动检测:auto </ param>
        /// <param name =“toLanguage”>中文:zh-CN,中文:en </ param>
        /// <returns>翻译后文本</ returns>
        public string GoogleTranslate(字符串文本,字符串fromLanguage,string toLanguage)
        {
            CookieContainer cc = new CookieContainer();

            string GoogleTransBaseUrl =“https://translate.google.cn/”;

            var BaseResultHtml = GetResultHtml(GoogleTransBaseUrl,cc,“”);

            Regex re = new Regex(@“(?<= TKK =)(。*?)(?= );)”);

            var TKKStr = re.Match(BaseResultHtml).ToString() “)”; //在返回的HTML中正则匹配TKK的JS代码

            var TKK = ExecuteScript(TKKStr,TKKStr); //执行TKK代码,得到TKK值

            var GetTkkJS = File.ReadAllText(@“gettk.js”);

            var tk = ExecuteScript(“tk(”“  text  ”“,”“  TKK  ”“)”,GetTkkJS);

            string googleTransUrl =“https://translate.google.cn/translate_a/single?client=t&sl=”  fromLanguage  “&tl =”  toLanguage  “&hl = en&dt = at&dt = bd&dt = ex&dt = ld&dt = md&dt = qca&dt = rw&dt = rm&dt = ss&dt = t&ie = UTF-8&oe = UTF-8&otf = 1&ssel = 0&tsel = 0&kc = 1&tk =“  tk  ”&q =“  HttpUtility.UrlEncode(text);

            var ResultHtml = GetResultHtml(googleTransUrl,cc,“”);

            dynamic TempResult = Newtonsoft.Json.JsonConvert.DeserializeObject(ResultHtml);

            string ResultText = Convert.ToString(TempResult [0] [0] [0]);

            return ResultText;
        }

        public string GetResultHtml(string url,CookieContainer cookie,string referer)
        {
            var html =“”;

            var webRequest = WebRequest.Create(url)as HttpWebRequest;

            webRequest.Method =“GET”;

            webRequest.CookieContainer = cookie;

            webRequest.Referer = referer;

            webRequest.Timeout = 20000;

            webRequest.Headers.Add( “X-请求-随着:XMLHttpRequest的”);

            webRequest.Accept =“text / html,application / xhtml   xml,application / xml; q = 0.9,image / webp,* / *; q = 0.8”;

            webRequest.UserAgent = url; // useragent;

            使用(var webResponse =(HttpWebResponse)webRequest.GetResponse())
            {
                使用(var reader = new StreamReader(webResponse.GetResponseStream(),Encoding.UTF8))
                {

                    html = reader.ReadToEnd();
                    reader.Close();
                    webResponse.Close();
                }
            }
            返回html;
        }

        /// <summary>
        ///执行JS
        /// </ summary>
        /// <param name =“sExpression”>参数体</ param>
        /// <param name =“sCode”> JavaScript代码的字符串</ param>
        /// <returns> </ returns>
        私有字符串ExecuteScript(字符串sExpression,字符串sCode)
        {
            MSScriptControl.ScriptControl scriptControl = new MSScriptControl.ScriptControl();
            scriptControl.UseSafeSubset = true;
            scriptControl.Language =“JScript”;
            scriptControl.AddCode(SCODE);
            尝试
            {
                string str = scriptControl.Eval(sExpression).ToString();
                返回str;
            }
            catch(Exception ex)
            {
                string str = ex.Message;
            }
            return null;
        } 
        #endregion

        /// <summary>正则校验
        /// </ summary>
        /// <param name =“str”> </ param>
        /// <param name =“matchStr”>正则</ param>
        /// <returns> </ returns>
        public static bool ValidateStr(string str,string matchStr)
        {
            尝试
            {
                return System.Text.RegularExpressions.Regex.IsMatch(str,matchStr);
            }
            catch(例外)
            {
                返回false;
            }
        }
        /// <summary>
        ///谷歌翻译
        /// </ summary>
        /// <param name =“text”>待翻译文本</ param>
        /// <param name =“fromLanguage”>自动检测:auto </ param>
        /// <param name =“toLanguage”>中文:zh-CN,中文:en </ param>
        /// <returns>翻译后文本</ returns>
        public string GoogleTranslate(字符串文本,字符串fromLanguage,string toLanguage)
        {
            CookieContainer cc = new CookieContainer();

            string GoogleTransBaseUrl =“https://translate.google.cn/”;

            var BaseResultHtml = GetResultHtml(GoogleTransBaseUrl,cc,“”);

            Regex re = new Regex(@“(?<= TKK =)(。*?)(?= );)”);

            var TKKStr = re.Match(BaseResultHtml).ToString() “)”; //在返回的HTML中正则匹配TKK的JS代码

            var TKK = ExecuteScript(TKKStr,TKKStr); //执行TKK代码,得到TKK值

            var GetTkkJS = File.ReadAllText(@“gettk.js”);

            var tk = ExecuteScript(“tk(”“  text  ”“,”“  TKK  ”“)”,GetTkkJS);

            string googleTransUrl =“https://translate.google.cn/translate_a/single?client=t&sl=”  fromLanguage  “&tl =”  toLanguage  “&hl = en&dt = at&dt = bd&dt = ex&dt = ld&dt = md&dt = qca&dt = rw&dt = rm&dt = ss&dt = t&ie = UTF-8&oe = UTF-8&otf = 1&ssel = 0&tsel = 0&kc = 1&tk =“  tk  ”&q =“  HttpUtility.UrlEncode(text);

            var ResultHtml = GetResultHtml(googleTransUrl,cc,“”);

            dynamic TempResult = Newtonsoft.Json.JsonConvert.DeserializeObject(ResultHtml);

            string ResultText = Convert.ToString(TempResult [0] [0] [0]);

            return ResultText;
        }

        public string GetResultHtml(string url,CookieContainer cookie,string referer)
        {
            var html =“”;

            var webRequest = WebRequest.Create(url)as HttpWebRequest;

            webRequest.Method =“GET”;

            webRequest.CookieContainer = cookie;

            webRequest.Referer = referer;

            webRequest.Timeout = 20000;

            webRequest.Headers.Add( “X-请求-随着:XMLHttpRequest的”);

            webRequest.Accept =“text / html,application / xhtml   xml,application / xml; q = 0.9,image / webp,* / *; q = 0.8”;

            webRequest.UserAgent = url; // useragent;

            使用(var webResponse =(HttpWebResponse)webRequest.GetResponse())
            {
                使用(var reader = new StreamReader(webResponse.GetResponseStream(),Encoding.UTF8))
                {

                    html = reader.ReadToEnd();
                    reader.Close();
                    webResponse.Close();
                }
            }
            返回html;
        }

        /// <summary>
        ///执行JS
        /// </ summary>
        /// <param name =“sExpression”>参数体</ param>
        /// <param name =“sCode”> JavaScript代码的字符串</ param>
        /// <returns> </ returns>
        私有字符串ExecuteScript(字符串sExpression,字符串sCode)
        {
            MSScriptControl.ScriptControl scriptControl = new MSScriptControl.ScriptControl();
            scriptControl.UseSafeSubset = true;
            scriptControl.Language =“JScript”;
            scriptControl.AddCode(SCODE);
            尝试
            {
                string str = scriptControl.Eval(sExpression).ToString();
                返回str;
            }
            catch(Exception ex)
            {
                string str = ex.Message;
            }
            return null;
        } 
        #endregion

界面呈现:

代码语言:javascript复制
<span style="color:#0000ff"><a data-cke-saved-href="https://jq.qq.com/?_wv=1027&k=579ylkn" href="https://jq.qq.com/?_wv=1027&k=579ylkn">点击加入QQ群,一起学习交流</a></span>

0 人点赞