首页 > 学院 > 开发设计 > 正文

百度翻译cs文件英文注释

2019-11-14 13:43:49
字体:
来源:转载
供稿:网友

原由:本人英语烂,没办法看不懂国外的代码注释!只能借助其他手段来助我一臂之力了. 虽然翻译内容不是很准确,但好过什么都看不懂的强. 对吧?!

代码有点乱有用的园友自个整理一下吧! 最近没时间所以翻译后内容保存还未实现,需不需要保存自个看着办吧!过段时间再整理实现一下!这只是一个简单的例子.

不足之处请大侠指出,在下感激不尽!

直接贴代码:

 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, "");        }    }

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表