/// <summary> /// 百度翻译 /// </summary> /// <param name="srcText">源文本</param> /// <param name="from">源语言</param> /// <param name="to">目标语言</param> public static string Translate(string srcText, string from, string to, string appid = null, string password = null) { string salt = DateTime.Now.Millisecond.ToString(); string id = appid ?? BaiduKey.AppId; string psd = password ?? BaiduKey.Password; // 签名 string sign = GetTranslateMD5(id + srcText + salt + psd); string url = "https://fanyi-api.baidu.com/api/trans/vip/translate"; string str = string.Format($"q={HttpUtility.UrlEncode(srcText)}&from={GetTranLang(from)}&to={GetTranLang(to)}" + $"&appid={id}&salt={salt}&sign={sign}"); string result = WebExt.Request(url, null, str); JavaScriptSerializer js = new JavaScriptSerializer(); // 实例化一个能够序列化数据的类 BaiduTranslate list = js.Deserialize <BaiduTranslate>(result); // 将json数据转化为对象类型并赋值给list if (list.Error_code != null) // 如果调用Api出现错误 { throw new Exception("调用百度翻译失败" + "\n原因:" + list.Error_msg); } // 接收序列化后的数据 StringBuilder dst = new StringBuilder(); foreach (var item in list.Trans_result) { dst.Append(item.Dst + "\r\n"); } return(dst.ToString().TrimEnd('\r', '\n')); }
public static async void Translate(SoraMessage e, string text) { text = SoraMessage.Escape(text); try { var result = BaiduTranslate.GetTranslateResult(text); if (result.Success) { if (result.OriginalLanguage.Equals(result.TranslateLanguage)) { await Task.Delay(1000); result = BaiduTranslate.GetTranslateResult(text, result.OriginalLanguage?.Id ?? "zh", "en"); } if (result.Success) { await e.ReplyToOriginal(new StringBuilder() .AppendLine($"[{result.OriginalLanguage}=>{result.TranslateLanguage}]") .Append(result.TranslateString).ToString()); return; } } await e.ReplyToOriginal(new StringBuilder().Append("翻译失败,") .AppendLine(result.Info).Append(result.TipMessage).ToString()); } catch (Exception ex) { await e.ReplyToOriginal(new StringBuilder().Append("翻译失败,") .AppendLine(ex.GetFormatString()).ToString()); } }
// ReSharper disable once UnusedParameter.Local static void Main(string[] args) { //读取要翻译的Json文件 var jsonStr = GetFileJson(); var jsonData = JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonStr); var retDic = new Dictionary <string, string>(); foreach (var temp in jsonData) { //百度翻译 (注意,进去配置秘钥等信息) var from = BaiduTranslate.GetTranslate(temp.Value); //有道云翻译(注意,进去配置秘钥等信息) //var from = YoudaoyunTranslate.GetTranslate(temp.Value); retDic.TryAdd(temp.Key, from); } var retJson = JsonConvert.SerializeObject(retDic); File.WriteAllText(@"..\..\..\baidu.json", retJson, Encoding.UTF8); }
void work_DoWork(object sender, DoWorkEventArgs e) { object transLate = new Object(); Type type = null; switch (TeanslateApi) { case "百度Baidu": transLate = new BaiduTranslate(); type = typeof(BaiduTranslate); break; case "谷歌Google": transLate = new GoogleTranslate(); type = typeof(GoogleTranslate); break; case "腾讯Tencent": transLate = new TencentTranslate(); type = typeof(TencentTranslate); break; case "必应Bing": translation = (new BingTranslate()).必应Bing(textBox1.Text); return; } string 原文语言 = TDictionary.langDic[TeanslateApi][label2.Text]; lanTo = TDictionary.langDic[TeanslateApi][label4.Text]; MethodInfo mt = type.GetMethod(TeanslateApi); translation = (string)mt.Invoke(transLate, new object[] { textBox1.Text, 原文语言, lanTo }); }
// 翻译 public static void Translate(string srcText, string from, string to, out string src_text, out string dst_text) { if (BaiduKey.IsEmptyOrNull) { throw new Exception("请设置百度文字识别和翻译Key!"); } // 源语言 string languageSrc = from; // 目标语言 string languageTo = to; //string languageTo = "zh"; // 随机数 string randomNum = DateTime.Now.Millisecond.ToString(); // md5编码 string md5Enc = GetMD5(BaiduKey.AppId + srcText + randomNum + BaiduKey.Password); // url string url = string.Format("https://fanyi-api.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}", HttpUtility.UrlEncode(srcText, Encoding.UTF8), languageSrc, languageTo, BaiduKey.AppId, randomNum, md5Enc); string result; using (WebClient wc = new WebClient()) result = wc.DownloadString(url); JavaScriptSerializer js = new JavaScriptSerializer(); // 实例化一个能够序列化数据的类 BaiduTranslate list = js.Deserialize <BaiduTranslate>(result); // 将json数据转化为对象类型并赋值给list if (list.Error_code != null) // 如果调用Api出现错误 { throw new Exception("调用百度翻译失败" + "\n原因:" + list.Error_msg); } // 接收序列化后的数据 StringBuilder dst = new StringBuilder(); StringBuilder src = new StringBuilder(); foreach (var item in list.Trans_result) { src.Append(item.Src + "\r\n"); dst.Append(item.Dst + "\r\n"); } int sLen = src.ToString().LastIndexOf('\r'); int dLen = dst.ToString().LastIndexOf('\r'); src_text = src.ToString().Remove(sLen); dst_text = dst.ToString().Remove(dLen); }
static void Main(string[] args) { //Test for Baidu translate BaiduTranslate.appId = "replace your id"; BaiduTranslate.secretKey = "replace your key"; var dst = BaiduTranslate.Baidu_Translate(baidu_lan.auto.ToString(), baidu_lan.en.ToString(), "百度翻译测试").Result; Console.WriteLine(dst); Console.WriteLine("\n\r"); //Test for Bing translate BingTranslate.Ocp_Apim_Subscription_Key = "replace your key"; var result = BingTranslate.Bing_Translate("zh-Hans", bing_lan.en.ToString(), "必应翻译测试").Result; Console.WriteLine(result); Console.Read(); }
private string Translate(string str) { object transLate = new Object(); Type type = null; switch (translateApi) { case "百度Baidu": transLate = new BaiduTranslate(); type = typeof(BaiduTranslate); break; case "腾讯Tencent": transLate = new TencentTranslate(); type = typeof(TencentTranslate); break; } MethodInfo mt = type.GetMethod(translateApi); return((string)mt.Invoke(transLate, new object[] { str, "auto", lanToVaule }));; }
/// <summary> /// 翻译 /// </summary> /// <param name="query"></param> /// <param name="from"></param> /// <param name="to"></param> /// <returns></returns> public static string Translate(string query, string from = "auto", string to = "zh") { return(BaiduTranslate.Translation(query, from, to)); }