unity文档注释翻译为中文

请添加图片描述
请添加图片描述
请添加图片描述

感谢:
绿云牧歌提供的翻译文档方法:https://blog.csdn.net/qq_32069969/article/details/88360608
我扶奶奶过哈登提供的调用百度翻译API方法:https://blog.csdn.net/u014571132/article/details/53334930
百度翻译提供的免费API

为了使用此功能,你需要前往https://fanyi-api.baidu.com/doc/21获得百度翻译的调用API权限。
免费档的权限为每秒钟1条,每次上限5000字。

/// 
/// 百度翻译API
/// 
class BaiduTranslation
{
	readonly string ID;
	readonly string Key;
	readonly int delay;
	const string API_URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";
	/// 
	/// 实例化一个对接百度翻译的对象。你需要从这里获取使用权限: https://fanyi-api.baidu.com/api/trans/product/desktop?req=developer
	/// 
	/// 百度提供的ID
	/// 百度提供的密钥
	/// 每次请求前的延迟。默认为最低档的1000毫秒
	public BaiduTranslation(string APPID, string 密钥, int delay = 1000)
	{
		this.delay = delay;
		ID = APPID;
		Key = 密钥;
	}
	/// 
	/// MD5加密算法
	/// 
	/// 希望加密的字符串
	/// 加密后的字符串
	string GetMD5HashFromFile(string strToHash)
	{
		try
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			using System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
			foreach (var item in md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strToHash)))
				sb.Append(Convert.ToString(item, 16).PadLeft(2, '0'));
			return sb.ToString();
		}
		catch (Exception ex)
		{
			Console.WriteLine("Message " + System.DateTime.Now.ToLongTimeString() + " :" + ex.Message);//MessageLog
			return "Md5 Error";
		}
	}
	/// 
	/// 发送一个翻译请求
	/// 
	/// 源字符串
	/// 源语种
	/// 目标语种
	/// 序列化后的输出
	public TranslationResult GetTranslation(string source, string from = Language.自动检测, string to = Language.自动检测)
	{
		try
		{
			Task.Delay(delay).Wait();
			string jsonResult = string.Empty;
			string randomNum = System.DateTime.Now.Millisecond.ToString();
			string md5Sign = GetMD5HashFromFile(ID + source + randomNum + Key);
			string utf8 = System.Web.HttpUtility.UrlEncode(source, System.Text.Encoding.UTF8);
			string url = $"{API_URL}?q={utf8}&from={from}&to={to}&appid={ID}&salt={randomNum}&sign={md5Sign }";
			using System.Net.WebClient wc = new System.Net.WebClient();
			return new Nancy.Json.JavaScriptSerializer().Deserialize<TranslationResult>(wc.DownloadString(url));
		}
		catch (Exception e)
		{
			Console.WriteLine(e.Message);
			return null;
		}
	}
	/// 
	/// 接收百度翻译API结果的实体类
	/// 
	public class TranslationResult
	{
		/// 
		/// 错误码
		/// 
		public string Error_code { get; set; }
		public string Error_msg { get; set; }
		/// 
		/// 源语种
		/// 
		public string From { get; set; }
		/// 
		/// 目标语种
		/// 
		public string To { get; set; }
		public string Query { get; set; }
		/// 
		/// 翻译结果(按段落分为数组)
		/// 
		public Translation[] Trans_result { get; set; }
		/// 
		/// 每个段落的翻译
		/// 
		public class Translation
		{
			/// 
			/// 源字符串
			/// 
			public string Src { get; set; }
			/// 
			/// 翻译后的字符串
			/// 
			public string Dst { get; set; }
		}
	}
	/// 
	/// 语种的代码(仅常用)
	/// 全部的语种请访问 https://fanyi-api.baidu.com/doc/21
	/// 
	public static class Language
	{
		public const string 自动检测 = "auto";
		public const string 中文 = "zh";
		public const string 英语 = "en";
		public const string 粤语 = "yue";
		public const string 文言文 = "wyw";
		public const string 日语 = "jp";
		public const string 韩语 = "kor";
		public const string 法语 = "fra";
		public const string 西班牙语 = "spa";
		public const string 泰语 = "th";
		public const string 阿拉伯语 = "ara";
		public const string 俄语 = "ru";
		public const string 葡萄牙语 = "pt";
		public const string 德语 = "de";
		public const string 意大利语 = "it";
		public const string 希腊语 = "el";
		public const string 荷兰语 = "nl";
		public const string 波兰语 = "pl";
		public const string 保加利亚语 = "bul";
		public const string 爱沙尼亚语 = "est";
		public const string 丹麦语 = "dan";
		public const string 芬兰语 = "fin";
		public const string 捷克语 = "cs";
		public const string 罗马尼亚语 = "rom";
		public const string 斯洛文尼亚语 = "slo";
		public const string 瑞典语 = "swe";
		public const string 匈牙利语 = "hu";
		public const string 繁体中文 = "cht";
		public const string 越南语 = "vie";
	}
}
/// 
/// 文档翻译类
/// 
class TranslationDocumentation
{
	BaiduTranslation baidu;
	/// 
	/// 需要一个百度翻译的实例对象作为参数
	/// 
	/// 
	public TranslationDocumentation(BaiduTranslation baidu)
	{
		this.baidu = baidu;
	}
	/// 
	/// 翻译目标文件夹下所有xml文件。如果有需要翻译的文件,会在目标文件夹下创建zh-hans文件夹。
	/// 翻译后的xml会放在zh-hans中。
	/// 
	/// 文件夹路径
	/// 是否在目标文件存在时跳过,默认跳过
	public void Analysis(string url, bool pass = true)
	{
		var v = Directory.GetFiles(url).Where(i => Path.GetExtension(i) == ".xml");
		var num = v.Count();
		if (num == 0)
		{
			Console.WriteLine("未找到xml文件");
			return;
		}
		Console.WriteLine($"共找到{num}项xml文件");
		Directory.CreateDirectory(url + @"\zh-hans");
		foreach (var item in v)
		{
			var exist = url + @"\zh-hans\" + Path.GetFileName(item);
			if (pass && File.Exists(exist))
				Console.WriteLine($"剩余{--num}项,因文件存在而跳过任务{item}");
			else
			{
				Console.WriteLine($"剩余{--num}项,正在翻译{item}");
				Translation(item, exist);
			}
		}
	}
	void Translation(string file, string save)
	{
		System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
		doc.Load(file);
		var xnl = doc.SelectSingleNode("doc/members");
		System.Text.StringBuilder sb = new System.Text.StringBuilder();
		recursion(xnl, (node) =>
		{

			bool isFirstLine = true;
			foreach (var line in node.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
			{
				if (string.IsNullOrWhiteSpace(line)) continue;
				if (isFirstLine)
					isFirstLine = false;
				else
					sb.Append(' ');
				sb.Append(line.Trim());
			}
			sb.Append("\n");
		});
		Dictionary<string, string> dic = new Dictionary<string, string>();
		foreach (var item in Gradually(sb.ToString().Split('\n')).SelectMany(i => i))
			dic[item.Src] = item.Dst;
		recursion(xnl, (node) =>
		{
			if (node.Value == null || !dic.ContainsKey(node.Value)) return;
			node.Value = dic[node.Value];
		});
		doc.Save(save);
	}
	void recursion(System.Xml.XmlNode node, Action<System.Xml.XmlNode> Process)
	{
		if (node.NodeType == System.Xml.XmlNodeType.Text)
			Process(node);
		else
			foreach (System.Xml.XmlNode item in node.ChildNodes)
				recursion(item, Process);
	}

	IEnumerable<IEnumerable<BaiduTranslation.TranslationResult.Translation>> Gradually(string[] s)
	{
		int num = 0; int surplus = s.Length;
		List<string> list = new List<string>();
		foreach (var item in s)
		{
			surplus--;
			list.Add(item);
			if ((num += item.Length) > 4000)
			{
				Console.WriteLine($"剩余{surplus}");
				yield return baidu.GetTranslation(string.Join('\n', list)).Trans_result;
				list.Clear();
				num = 0;
			}
		}
		yield return baidu.GetTranslation(string.Join('\n', list)).Trans_result;
	}
}

如何调用:
在这里插入图片描述

你可能感兴趣的:(#,c#杂物,unity)