事情需要,把一个措施翻译为多语言版,很悲催的此中一个语种为土耳其语.国内开放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>待翻译文本</param>
/// <param>自动检测:auto</param>
/// <param>中文: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>参数体</param>
/// <param>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,汉字转码,发送翻译请求的时候使用.
标签:
原文地点:https://www.cnblogs.com/FrankSz/p/8962370.html