查找unity工程代码中中文字符

游戏本地化的时候可能需要搜索工程代码中的中文字符。

这个可以通过加载文件一行一行读取后,通过正则来查询。

下面的代码LoadFile函数通过流加载文件,FindFile通过递归病使用DirectoryInfo类和FileInfo类读取子目录和文件,并通过正则匹配出中文字符。

使用时需要引用

using System.Text.RegularExpressions;
using System.IO;




        



<span style="white-space:pre">	</span>public static ArrayList infoall;
	public static List<string> FileNames = new List<string>(); 
	[MenuItem("Localization/Check Porject Chinese File")]
	public static void CheckChinese()
	{
		FileNames.Clear ();
		string dir = Application.dataPath + "/Scripts";
		FindFile(dir);
		Debug.Log ("包含中文的文件共" + FileNames.Count + "个");
		for(int i = 0; i < FileNames.Count; i++)
		{
			Debug.Log ("包含中文的文件" + i +"           " + FileNames[i]);
		}
	}

	public static ArrayList LoadFile(string path,string name)
	{
		//使用流的形式读取
		StreamReader sr =null;
		try{
			sr = File.OpenText(path+"//"+ name);
		}catch(Exception e)
		{
			//路径与名称未找到文件则直接返回空
			return null;
		}
		string line;
		ArrayList arrlist = new ArrayList();
		while ((line = sr.ReadLine()) != null)
		{
			//一行一行的读取
			//将每一行的内容存入数组链表容器中
			arrlist.Add(line);
		}
		//关闭流
		sr.Close();
		//销毁流
		sr.Dispose();
		//将数组链表容器返回
		return arrlist;
	} 
	public static void FindFile(string dirPath) //参数dirPath为指定的目录
	{
		//在指定目录及子目录下查找文件,在listBox1中列出子目录及文件
		DirectoryInfo Dir=new DirectoryInfo(dirPath);
		foreach(DirectoryInfo d in Dir.GetDirectories())//查找子目录
		{
			FindFile(d.FullName);
		}
		foreach(FileInfo f in Dir.GetFiles("*.cs")) //查找文件
		{
			bool haveChinese = false;
			infoall = LoadFile(Dir.ToString(),f.Name);
			Regex rxChinaCharacter = new Regex ("[\u4e00-\u9fa5]+");  //正则匹配中文字符
			for(int i = 0 ;i < infoall.Count;i++)
			{
				MatchCollection matches = rxChinaCharacter.Matches(infoall[i].ToString());
				if (matches.Count > 0)
				{
					haveChinese = true;
					Debug.Log("文件名:"+f.FullName + "                     行号:"+ i + "                   内容" + infoall[i].ToString());
				}
			}
			if(haveChinese)
				FileNames.Add(f.FullName);
			
		}
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值