天天看點

.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, @"[\n\r]", "");
            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;
        }
    }
}      
BaiDuJS.dll下載下傳位址:https://files.cnblogs.com/files/wang920607/baidujs.7z      

有道翻譯代碼實作:

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", "[email protected]; 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。