原由:本人英語爛,沒辦法看不懂國外的代碼注釋!只能借助其他手段來助我一臂之力了. 雖然翻譯內容不是很准確,但好過什麼都看不懂的強. 對吧?!
代碼有點亂有用的園友自個整理一下吧! 最近沒時間所以翻譯後內容保存還未實現,需不需要保存自個看著辦吧!過段時間再整理實現一下!這只是一個簡單的例子.
不足之處請大俠指出,在下感激不盡!
直接貼代碼:
class Program { private readonly string appid = "XXXXXXXXXXXXXXXXXX";//APPID private readonly string sec_key = "XXXXXXXXXXXXXXXXXXXX";//私鑰 private readonly string from = "en"; private readonly string to = "yue"; private readonly string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?"; static void Main(string[] args) { new Program().Run(); } private void Run() { string path = Directory.GetCurrentDirectory(); Console.WriteLine("起始目錄:" + path); IList<FileInfo> files = GetFiles(path); Console.WriteLine("File Size:" + files.Count); ConcurrentQueue<FileInfo> cq = new ConcurrentQueue<FileInfo>(); Parallel.ForEach(files, (e) => { cq.Enqueue(e); }); Parallel.ForEach(cq, (e) => { // 讀取cs文件內容 List<String> rcq = ReaderLine(e.FullName); Console.WriteLine(e.FullName + "翻譯中..."); // 遍歷cs文件代碼行 foreach (String q in rcq) { if (!StringHandle.isNote(q)) continue;// 判斷是否是注釋 string note = StringHandle.GetNoteValue(q);// 獲取注釋內容 if (string.IsNullOrWhiteSpace(note)) continue; // 組織url參數 // string pars = GetUrlPars("2015063000000001", "12345678", "hello", from, to); string pars = GetUrlPars(appid, sec_key, note.Trim(), from, to); // 翻譯 // 返回格式:{"from":"en","to":"zh","trans_result":[{"src":"using System;","dst":"\u4f7f\u7528\u7cfb\u7edf\uff1b"}]} string result = GetUrltoHtml(url + pars); //反序列化結果 LanguageInfo info = Serialization<LanguageInfo>(result); if (info.IsNull) { ErrorInfo error = Serialization<ErrorInfo>(result); Console.WriteLine("---Error:" + error.error_code + " --- " + error.error_msg + " --- " + error.CodeToMsg()); } else { Console.WriteLine("原文:"+info.trans_result[0].src); Console.WriteLine("譯文:"+info.trans_result[0].dst); Console.WriteLine(); } } }); Console.ReadKey(); } private Random r = new Random(int.MaxValue); /// <summary> /// 拼接地址參數 /// </summary> /// <param name="appid">APPID</param> /// <param name="sec_key">私鑰</param> /// <param name="q">翻譯query</param> /// <param name="from"></param> /// <param name="to"></param> /// <returns></returns> public string GetUrlPars(string appid,string sec_key,string q,string from,string to) { StringBuilder sb = new StringBuilder(); sb.Append("appid=" + appid); // 隨機數 var salt = r.Next(1000000, int.MaxValue).ToString(); sb.Append("&salt=" + salt); sb.Append("&from=" + from); sb.Append("&to=" + to); sb.Append("&q=" + HttpUtility.UrlEncode(q, Encoding.GetEncoding("GB2312"))); //對 appid + 翻譯內容 + 隨機數 + 私鑰 進行MD5加密 var sign = MD5Encrypt(appid + q + salt + sec_key, Encoding.Default); sb.Append("&sign=" + sign); return sb.ToString(); } /// <summary> /// 讀取文件 /// </summary> /// <param name="path"></param> /// <returns></returns> public List<String> ReaderLine(string path) { StreamReader sr = new StreamReader(path, Encoding.Default); List<String> lines = new List<string>(); string line; while ((line = sr.ReadLine()) != null) { lines.Add(line); } sr.Close(); return lines; } /// <summary> /// 反序列化JSON /// </summary> /// <param name="obj"></param> /// <returns></returns> private T Serialization<T>(string obj)where T:class { using (var mStream = new MemoryStream(Encoding.UTF8.GetBytes(obj))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); T entity = serializer.ReadObject(mStream) as T; return entity; } } /// <summary> /// 遍歷當前目錄及子目錄 /// </summary> /// <param name="strPath">文件路徑</param> /// <returns>所有文件</returns> private static IList<FileInfo> GetFiles(string strPath) { List<FileInfo> lstFiles = new List<FileInfo>(); List<string> lstDirect = new List<string>(); lstDirect.Add(strPath); DirectoryInfo diFliles = null; GetDirectorys(strPath, ref lstDirect); foreach (string str in lstDirect) { try { diFliles = new DirectoryInfo(str); lstFiles.AddRange(diFliles.GetFiles("*.cs")); } catch { continue; } } return lstFiles; } private static void GetDirectorys(string strPath, ref List<string> lstDirect) { DirectoryInfo diFliles = new DirectoryInfo(strPath); DirectoryInfo[] diArr = diFliles.GetDirectories(); //DirectorySecurity directorySecurity = null; foreach (DirectoryInfo di in diArr) { try { //directorySecurity = new DirectorySecurity(di.FullName, AccessControlSections.Access); //if (!directorySecurity.AreAccessRulesProtected) //{ lstDirect.Add(di.FullName); GetDirectorys(di.FullName, ref lstDirect); //} } catch { continue; } } } /// <summary> /// MD5加密 /// </summary> /// <param name="input">需要加密的字符串</param> /// <param name="encode">字符的編碼</param> /// <returns></returns> public static string MD5Encrypt(string input, Encoding encode) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] t = md5.ComputeHash(encode.GetBytes(input)); StringBuilder sb = new StringBuilder(32); for (int i = 0; i < t.Length; i++) sb.Append(t[i].ToString("x").PadLeft(2, '0')); return sb.ToString(); } /// <summary> /// 傳入URL返回網頁的html代碼 /// </summary> /// <param name="Url">URL</param> /// <returns></returns> public string GetUrltoHtml(string Url) { StringBuilder content = new StringBuilder(); try { //這一句一定要寫在創建連接的前面。使用回調的方法進行證書驗證。 //ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); // 與指定URL創建HTTP請求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //創建證書文件 //X509Certificate objx509 = new X509Certificate(System.Net.Mime.MediaTypeNames.Application.StartupPath + "\\123.cer"); //添加到請求裡 //request.ClientCertificates.Add(objx509); // 獲取對應HTTP請求的響應 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 獲取響應流 Stream responseStream = response.GetResponseStream(); // 對接響應流(以"GBK"字符集) StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 開始讀取數據 Char[] sReaderBuffer = new Char[256]; int count = sReader.Read(sReaderBuffer, 0, 256); while (count > 0) { String tempStr = new String(sReaderBuffer, 0, count); content.Append(tempStr); count = sReader.Read(sReaderBuffer, 0, 256); } // 讀取結束 sReader.Close(); } catch (Exception) { content = new StringBuilder("Runtime Error"); } return content.ToString(); } }
/* {"from":"en","to":"zh","trans_result":[{"src":"using System;","dst":"\u4f7f\u7528\u7cfb\u7edf\uff1b"}]} */ [DataContract] //翻譯語言結果 public class LanguageInfo { [DataMember] public string from { get; set; } [DataMember] public string to { get; set; } [DataMember] public ResultInfo[] trans_result { get; set; } public bool IsNull { get { return (string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to) && trans_result == null); } } } [DataContract] public class ResultInfo { [DataMember] //原文 public string src{get;set;} [DataMember] //譯文 public string dst{get;set;} } /* {"error_code":"54001","error_msg":"Invalid Sign"} */ [DataContract] //錯誤信息 public class ErrorInfo { [DataMember] public string error_code { get; set; } [DataMember] public string error_msg { get; set; } public string CodeToMsg() { switch (error_code) { case "52001":return "請求超時 重試"; case "52002":return "系統錯誤 重試"; case "52003":return "未授權用戶 檢查您的appid 是否正確"; case "54000":return "必填參數為空 檢查是否少傳參數"; case "58000":return "客戶端IP非法 檢查個人資料裡填寫的IP地址是否正確"; case "54001":return "簽名錯誤 請檢查您的簽名生成方法"; case "54003":return "訪問頻率受限 請降低您的調用頻率"; case "58001":return "譯文語言方向不支持 檢查譯文語言是否在語言列表裡"; case "54004":return "賬戶余額不足 請前往管理控制平台為賬戶充值"; default: return "完了,都不知道什麼錯了!"; } } }
public static class StringHandle { private static Regex regIsNote = new Regex(@"(///|//)"); private static Regex regGetNote = new Regex(@"(///\s+)|((<|</)summary>)|((<|</)param>)|((<|</)returns>)"); /// <summary> /// 是否注釋正文 /// </summary> /// <param name="str">字符串</param> /// <returns></returns> public static bool isNote(string str) { return regIsNote.IsMatch(str); } /// <summary> /// 獲取注釋值 /// </summary> /// <param name="str">注釋</param> /// <returns></returns> public static string GetNoteValue(string str) { return regGetNote.Replace(str, ""); } }