码迷,mamicode.com
首页 > Windows程序 > 详细

使用谷歌翻译C#版本.

时间:2018-04-27 15:44:56      阅读:512      评论:0      收藏:0      [点我收藏+]

标签:text   pre   亲测   内容   国内   .net   ref   开发工具   sub   

工作需要,把一个程序翻译为多语言版,很悲催的其中一个语种为土耳其语.国内开放API的翻译均不支持.微软的实在是麻烦.网上找到一个c#版,修修改改,凑合用.亲测有效.

开发工具:VS2013

需要引用多个单元

using System.Web;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;
using MSScriptControl;

需要多个引用包.

 

//引用-->添加引用-->com-->类型库,注意引用该库后程序环境必须为X86.更改项目属性即可,影响不大   js解析包
//引用-->添加引用-->选择最近项目-->Newtonsoft.Json.dll     json解析库.该DLL网上可以下载

网上要保存js文件,我直接写成全局变量

string GetTkkJS = @"
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 : Number(c),
c = ""+"" == b.charAt(d + 1) ? a >>> c : a << c;
a = ""+"" == b.charAt(d) ? a + c & 4294967295 : a ^ c
}
return a
}


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 ^= Number(e[1]) || 0;
0 > a && (a = (a & 2147483647) + 2147483648);
a %= 1E6;
return a.toString() + ""."" + (a ^ h)
}";

  核心执行代码如下:

 

       
        /// <summary>  
        /// 谷歌翻译  
        /// </summary>  
        /// <param name="text">待翻译文本</param>  
        /// <param name="fromLanguage">自动检测:auto</param>  
        /// <param name="toLanguage">中文:zh-CN,英文:en</param>  
        /// <returns>翻译后文本</returns>  
        public string GoogleTranslate(string text, string 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 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); //转换为json
//结果示例 //ResultText = ‘[[["I love you","我爱你",null,null,1],[null,null,null,"Wǒ ài nǐ"]],null,"zh-CN",null,null,[["我爱你",null,[["I love you",1000,true,false]], // [[0,3]],"我爱你",0,0]],1,null,[["zh-CN"],null,[1],["zh-CN"]],null,null,null,null,null,[["我","爱","你"]]]‘ string ResultText = Convert.ToString(TempResult[0][0][0]); //数组json,第一个数组里边的第一个数组的第一个内容.嵌套数据, return ResultText; } public string GetResultHtml(string url, CookieContainer cookie, string referer) { var html = ""; var webRequest = WebRequest.Create(url) as HttpWebRequest; webRequest.Method = "GET"; /*网上程序代码,自己用chrome浏览器F12查看追踪修改为下列两行,同样执行成功.20180427 //webRequest.CookieContainer = cookie; //webRequest.Referer = referer; //webRequest.Timeout = 20000; //webRequest.Headers.Add("X-Requested-With:XMLHttpRequest"); //webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; webRequest.Accept = "*/*"; webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"; using (var webResponse = (HttpWebResponse)webRequest.GetResponse()) { using (var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)) { html = reader.ReadToEnd(); reader.Close(); webResponse.Close(); } } return html; } /// <summary> /// 执行JS /// </summary> /// <param name="sExpression">参数体</param> /// <param name="sCode">JavaScript代码的字符串</param> /// <returns></returns> private string ExecuteScript(string sExpression, string sCode) { MSScriptControl.ScriptControl scriptControl = new MSScriptControl.ScriptControl(); scriptControl.UseSafeSubset = true; scriptControl.Language = "JScript"; scriptControl.AddCode(sCode); try { string str = scriptControl.Eval(sExpression).ToString(); return str; } catch (Exception ex) { string str = ex.Message; } return null; }

  

有了此例子,后续准备扩展为Delphi.需要的知识如下:

idhttp get :http协议,

superobject: json库, 

TPerlRegEx:正则表达式

comObje:js

HTTPApp:httpEncode,汉字转码,发送翻译请求的时候使用.

使用谷歌翻译C#版本.

标签:text   pre   亲测   内容   国内   .net   ref   开发工具   sub   

原文地址:https://www.cnblogs.com/FrankSz/p/8962370.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!