博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
百度翻译cs文件英文注释
阅读量:5832 次
发布时间:2019-06-18

本文共 8453 字,大约阅读时间需要 28 分钟。

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

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

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

直接贴代码:

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
files = GetFiles(path); Console.WriteLine("File Size:" + files.Count); ConcurrentQueue
cq = new ConcurrentQueue
(); Parallel.ForEach(files, (e) => { cq.Enqueue(e); }); Parallel.ForEach(cq, (e) => { // 读取cs文件内容 List
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
(result); if (info.IsNull) { ErrorInfo error = Serialization
(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); ///
/// 拼接地址参数 /// ///
APPID ///
私钥 ///
翻译query ///
///
///
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(); } ///
/// 读取文件 /// ///
///
public List
ReaderLine(string path) { StreamReader sr = new StreamReader(path, Encoding.Default); List
lines = new List
(); string line; while ((line = sr.ReadLine()) != null) { lines.Add(line); } sr.Close(); return lines; } ///
/// 反序列化JSON /// ///
///
private T Serialization
(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; } } ///
/// 遍历当前目录及子目录 /// ///
文件路径 ///
所有文件
private static IList
GetFiles(string strPath) { List
lstFiles = new List
(); List
lstDirect = new List
(); 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
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; } } } ///
/// MD5加密 /// ///
需要加密的字符串 ///
字符的编码 ///
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(); } ///
/// 传入URL返回网页的html代码 /// ///
URL ///
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+)|((<|
)|((<|
)|((<|
)"); /// /// 是否注释正文 /// /// 字符串 ///
public static bool isNote(string str) { return regIsNote.IsMatch(str); } /// /// 获取注释值 /// /// 注释 ///
public static string GetNoteValue(string str) { return regGetNote.Replace(str, ""); } }

 

转载于:https://www.cnblogs.com/mycing/p/5007902.html

你可能感兴趣的文章
linq 学习笔记之 Linq基本子句
查看>>
[Js]布局转换
查看>>
Hot Bath
查看>>
国内常用NTP服务器地址及
查看>>
Java annotation 自定义注释@interface的用法
查看>>
Apache Spark 章节1
查看>>
phpcms与discuz的ucenter整合
查看>>
Linux crontab定时执行任务
查看>>
mysql root密码重置
查看>>
33蛇形填数
查看>>
选择排序
查看>>
SQL Server 数据库的数据和日志空间信息
查看>>
前端基础之JavaScript
查看>>
自己动手做个智能小车(6)
查看>>
自己遇到的,曾未知道的知识点
查看>>
P1382 楼房 set用法小结
查看>>
分类器性能度量
查看>>
windows 环境下切换 python2 与 pythone3 以及常用命令
查看>>
docker 基础
查看>>
解决灾难恢复后域共享目录SYSVOL与NELOGON共享丢失
查看>>