欢迎光临
我的个人博客网站

.NET C# 实现免费使用谷歌、百度、有道、小牛翻译接口

废话不多说,直接上代码。

谷歌翻译代码实现:

using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions;  namespace Google {     class Program     {         static void Main(string[] args)         {             Google();             Console.ReadKey();         }          public static void Google()         {             string url = "https://translate.google.cn/_/TranslateWebserverUi/data/batchexecute?rpcids=MkEWBc&bl=boq_translate-webserver_20210927.13_p0&soc-app=1&soc-platform=1&soc-device=1&rt=c";             string q = "The invention relates to a "three-dimensional structure" obtained from a tubular preform, which is obtained from a net of the Chebyshev type (with such a structure also being called "elastic gridshell") having a flared shape maintained by means selected from the group comprising hoops (5, 7, 9), spacers (11) and cables (11). The invention also relates to a method for installing such a structure, in which method the tubular preform is brought to the installation point, then deformations are applied to this preform that allow the final desired flared shape to be achieved. Particular application to the production of street furniture allowing shaded areas to be created in towns by cultivating everything that is fixed on a heavy container containing cultivated soil and the necessary devices.";             string from = "auto";             string to = "zh";             var from_data = "f.req=" + System.Web.HttpUtility.UrlEncode(                 string.Format("[[["MkEWBc","[[\"{0}\",\"{1}\",\"{2}\",true],[null]]", null, "generic"]]]",                 ReplaceString(q), from, to), Encoding.UTF8).Replace("+", "%20");             byte[] postData = Encoding.UTF8.GetBytes(from_data);             WebClient client = new WebClient();             client.Encoding = Encoding.UTF8;             client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");             client.Headers.Add("ContentLength", postData.Length.ToString());             client.Headers.Add("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");             client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36");             byte[] responseData = client.UploadData(url, "POST", postData);             string content = Encoding.UTF8.GetString(responseData);             Console.WriteLine(MatchResult(content));         }          /// <summary>         /// 匹配翻译结果         /// </summary>         /// <returns></returns>         public static string MatchResult(string content)         {             string result = "";             string patttern = @",[[\""(.*?)\"",";             Regex regex = new Regex(patttern);             MatchCollection matchcollection = regex.Matches(content);             if (matchcollection.Count > 0)             {                 List<string> list = new List<string>();                 foreach (Match match in matchcollection)                 {                     list.Add(match.Groups[1].Value);                 }                 result = string.Join(" ", list.Distinct());                 if (result.LastIndexOf(@"""]]]],""") > 0)                 {                     result = result.Substring(0, result.LastIndexOf(@"""]]]],"));                 }             }             return result;         }          /// <summary>         ///   替换部分字符串         /// </summary>         /// <param name="sPassed">需要替换的字符串</param>         /// <returns></returns>         public static string ReplaceString(string JsonString)         {             if (JsonString == null) { return JsonString; }             if (JsonString.Contains("\"))             {                 JsonString = JsonString.Replace("\", "\\");             }             if (JsonString.Contains("'"))             {                 JsonString = JsonString.Replace("'", "\'");             }             if (JsonString.Contains("""))             {                 JsonString = JsonString.Replace(""", "\\\"");             }             //去掉字符串的回车换行符             JsonString = Regex.Replace(JsonString, @"[nr]", "");             JsonString = JsonString.Trim();             return JsonString;         }     } }

百度翻译代码实现:

using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using Newtonsoft.Json.Linq; using Newtonsoft.Json;  namespace BaiDu {     class Program     {         static void Main(string[] args)         {             BaiDu();         }          public static void BaiDu()         {             string url = "https://fanyi.baidu.com/v2transapi";             string token = "c53e292ca5f022541702df60386b0940";             string gtk = "320305.131321201";             string q = "翻訳する内容を入力";             string from = LangDetect(q);             string to = "en";                     BaiDuJS bd = new BaiDuJS();             string sign = bd.e(q, gtk);             Dictionary<String, String> dic = new Dictionary<String, String>();             dic.Add("from", from);             dic.Add("to", to);             dic.Add("query", q);             dic.Add("transtype", "translang");             dic.Add("simple_means_flag", "3");             dic.Add("sign", sign);             dic.Add("token", token);             dic.Add("domain", "common");             StringBuilder builder = new StringBuilder();             int i = 0;             foreach (var item in dic)             {                 if (i > 0)                     builder.Append("&");                 builder.AppendFormat("{0}={1}", item.Key, item.Value);                 i++;             }             byte[] postData = Encoding.UTF8.GetBytes(builder.ToString());             WebClient client = new WebClient();             client.Encoding = Encoding.UTF8;             client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");             client.Headers.Add("ContentLength", postData.Length.ToString());             client.Headers.Add("Cookie", "PSTM=1632374651; BAIDUID=CA0CAE73A357CB8878FFB0D5549F647D:FG=1; BIDUPSID=9450FAB50ADD9DBAB8E00FDAC634C5FC; __yjs_duid=1_5165006a9fc9999dacd45b9431bd4e371632376111266; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; REALTIME_TRANS_SWITCH=1; SOUND_PREFER_SWITCH=1; SOUND_SPD_SWITCH=1; delPer=0; PSINO=2; BAIDUID_BFESS=CA0CAE73A357CB8878FFB0D5549F647D:FG=1; BCLID=11468570277037651377; BDSFRCVID=8n_OJexroG0YyvRH__3KKwxhtLweG7bTDYLEOwXPsp3LGJLVJeC6EG0Pts1-dEu-EHtdogKK0mOTHvtF_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF=tR3aQ5rtKRTffjrnhPF3yU7bXP6-hnjy3bRkX4nvWU7rhpvo5n7s5MAWbttf5q3RymJJ2-39LPO2hpRjyxv4y4Ldj4oxJpOJ-bCL0p5aHl51fbbvbURvD-ug3-7q-U5dtjTO2bc_5KnlfMQ_bf--QfbQ0hOhqP-jBRIEoCvt-5rDHJTg5DTjhPrMeMTdWMT-MTryKKJwM4QCOM73DURv5nkJ5-vfKx-fKHnRhlRNB-3iV-OxDUvnyxAZyxomtfQxtNRJQKDE5p5hKq5S5-OobUPUDMc9LUvqbgcdot5yBbc8eIna5hjkbfJBQttjQn3hfIkj2CKLK-oj-DKCj5jP; BCLID_BFESS=11468570277037651377; BDSFRCVID_BFESS=8n_OJexroG0YyvRH__3KKwxhtLweG7bTDYLEOwXPsp3LGJLVJeC6EG0Pts1-dEu-EHtdogKK0mOTHvtF_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF_BFESS=tR3aQ5rtKRTffjrnhPF3yU7bXP6-hnjy3bRkX4nvWU7rhpvo5n7s5MAWbttf5q3RymJJ2-39LPO2hpRjyxv4y4Ldj4oxJpOJ-bCL0p5aHl51fbbvbURvD-ug3-7q-U5dtjTO2bc_5KnlfMQ_bf--QfbQ0hOhqP-jBRIEoCvt-5rDHJTg5DTjhPrMeMTdWMT-MTryKKJwM4QCOM73DURv5nkJ5-vfKx-fKHnRhlRNB-3iV-OxDUvnyxAZyxomtfQxtNRJQKDE5p5hKq5S5-OobUPUDMc9LUvqbgcdot5yBbc8eIna5hjkbfJBQttjQn3hfIkj2CKLK-oj-DKCj5jP; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1632728579,1632728592,1632749927,1632750542; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1632750542; BAIDU_WISE_UID=wapp_1632789389096_918; ab_sr=1.0.1_MGM1ZGY2YWIzNjRlMzNjYTQ3ZDYyZmU4NmNkMGUyYjVhOWIyYWNhNGE4OWFkNTRjMDA1MTQ1MDU1MmI1NjAzMjA3MTk3NDI4ZmUwNTRjYTYyNjYyMWM4NDhjMThmZTIxMmNkNmJmZDMwOGVjYzM1MDExYTA3ODgyOTY5ZTNlNTY4Y2ExZmRhOGRiZGJjOTQ5ZGZlZGQ4NDdmOWE4ZTRiNA==; BDRCVFR[laz3IxV61qm]=mk3SLVN4HKm; H_PS_PSSID=26350; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; BA_HECTOR=8ka0al8gal2004ak3v1gl4s2i0r");             client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36");             byte[] responseData = client.UploadData(url, "POST", postData);             string content = Encoding.UTF8.GetString(responseData);             JObject jo = (JObject)JsonConvert.DeserializeObject(content);             var result = jo.SelectToken("trans_result").SelectToken("data").First().Value<string>("dst");             Console.WriteLine(result);             Console.ReadKey();         }          public static string LangDetect(string q)         {             string result = string.Empty;             string url = "https://fanyi.baidu.com/langdetect?query={0}";             if (q.Length > 50)             {                 q = q.Substring(0, 50);             }             WebClient client = new WebClient();             byte[] responseData = client.DownloadData(string.Format(url, q));             string content = Encoding.UTF8.GetString(responseData);             JObject ja = (JObject)JsonConvert.DeserializeObject(content);             result = ja.Value<string>("lan");             return result;         }     } }

有道翻译代码实现:

using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text;  namespace YouDao {     class Program     {         public static void Main()         {             YouDao("本发明涉及一种用于在与第二对话者进行电信(10)期间检测第一对话者(12)的意图(30)的保护装置(18)。保护装置(18)被构造用于借助于自动语音识别来识别电信(10)的对话序列(28)。保护装置(18)还被构造用于,将所识别的对话序列(28)与预先确定的对话序列模型(20)进行比较,其中,通过预先确定的对话序列模型(20)限定:在对话序列(28)的过程中由相应的语音信号(22)构成的哪个组合对应于第一对话参与者(12)的相应的意图(30)。保护装置还被设立用于,基于所识别的对话序列(28)和预先确定的对话序列模型(20)的比较(27)来识别第一对话参与者(12)的相应的意图(30),并且实施与相应的所识别的意图(30)相关联的预先确定的保护措施(32)。", "auto","en");         }          public static void YouDao(string q, string from, string to)         {             string result = "";             string url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule/";             string u = "fanyideskweb";             string c = "Y2FYu%TNSbMCxc3t2u^XT";             TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));             long millis = (long)ts.TotalMilliseconds;             string curtime = Convert.ToString(millis);             Random rd = new Random();             string f = curtime + rd.Next(0, 9);             string signStr = u + q + f + c;             string sign = GetMd5Str_32(signStr);             Dictionary<String, String> dic = new Dictionary<String, String>();             dic.Add("i", q);             dic.Add("from", from);             dic.Add("to", to);             dic.Add("smartresult", "dict");             dic.Add("client", "fanyideskweb");             dic.Add("salt", f);             dic.Add("sign", sign);             dic.Add("lts", curtime);             dic.Add("bv", GetMd5Str_32("5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"));             dic.Add("doctype", "json");             dic.Add("version", "2.1");             dic.Add("keyfrom", "fanyi.web");             dic.Add("action", "FY_BY_REALTlME");             //dic.Add("typoResult", "false");              HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);             req.Method = "POST";             req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";             req.Referer = "http://fanyi.youdao.com/";             req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36";             req.Headers.Add("Cookie", "OUTFOX_SEARCH_USER_ID=-2030520936@111.204.187.35; OUTFOX_SEARCH_USER_ID_NCOO=798307585.9506682; UM_distinctid=17c2157768a25e-087647b7cf38e8-581e311d-1fa400-17c2157768b8ac; P_INFO=15711476666|1632647789|1|youdao_zhiyun2018|00&99|null&null&null#bej&null#10#0|&0||15711476666; JSESSIONID=aaafZvxuue5Qk5_d9fLWx; ___rl__test__cookies=" + curtime);             StringBuilder builder = new StringBuilder();             int i = 0;             foreach (var item in dic)             {                 if (i > 0)                     builder.Append("&");                 builder.AppendFormat("{0}={1}", item.Key, item.Value);                 i++;             }             byte[] data = Encoding.UTF8.GetBytes(builder.ToString());             req.ContentLength = data.Length;             using (Stream reqStream = req.GetRequestStream())             {                 reqStream.Write(data, 0, data.Length);                 reqStream.Close();             }             HttpWebResponse resp = (HttpWebResponse)req.GetResponse();             Stream stream = resp.GetResponseStream();             using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))             {                 JObject jo = (JObject)JsonConvert.DeserializeObject(reader.ReadToEnd());                 if (jo.Value<string>("errorCode").Equals("0"))                 {                     var tgtarray = jo.SelectToken("translateResult").First().Values<string>("tgt").ToArray();                     result = string.Join("", tgtarray);                 }             }             Console.WriteLine(result);             Console.ReadKey();         }          public static string GetMd5Str_32(string encryptString)         {             byte[] result = Encoding.UTF8.GetBytes(encryptString);             MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();             byte[] output = md5.ComputeHash(result);             string encryptResult = BitConverter.ToString(output).Replace("-", "");             return encryptResult;         }     } }

小牛翻译代码实现:

using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Net; using System.Text;  namespace Niutrans {     class Program     {         static void Main(string[] args)         {             Niutrans("本发明涉及一种用于在与第二对话者进行电信(10)期间检测第一对话者(12)的意图(30)的保护装置(18)。保护装置(18)被构造用于借助于自动语音识别来识别电信(10)的对话序列(28)。保护装置(18)还被构造用于,将所识别的对话序列(28)与预先确定的对话序列模型(20)进行比较,其中,通过预先确定的对话序列模型(20)限定:在对话序列(28)的过程中由相应的语音信号(22)构成的哪个组合对应于第一对话参与者(12)的相应的意图(30)。保护装置还被设立用于,基于所识别的对话序列(28)和预先确定的对话序列模型(20)的比较(27)来识别第一对话参与者(12)的相应的意图(30),并且实施与相应的所识别的意图(30)相关联的预先确定的保护措施(32)。", "auto", "en");         }          public static void Niutrans(string q, string from, string to)         {             string result = string.Empty;             string url = string.Format("https://test.niutrans.com/NiuTransServer/testaligntrans?from={0}&to={1}&src_text={2}&source=text&dictNo=&memoryNo=&isUseDict=0&isUseMemory=0", from, to, q);             WebClient client = new WebClient();             client.Encoding = Encoding.UTF8;             client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36");             byte[] responseData = client.DownloadData(url);             string content = Encoding.GetEncoding("utf-8").GetString(responseData);             JObject jo = (JObject)JsonConvert.DeserializeObject(content);             result = jo.Value<string>("tgt_text");;             Console.WriteLine(result);             Console.ReadKey();         }     } }

综合推荐:谷歌>百度>有道>小牛

频繁调用有被封禁IP的风险,建议使用代理IP访问,参考https://www.cnblogs.com/wang920607/p/15378846.html。

赞(0) 打赏
未经允许不得转载:张拓的天空 » .NET C# 实现免费使用谷歌、百度、有道、小牛翻译接口
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

专业的IT技术经验分享 更专业 更方便

联系我们本站主机

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏