(2)读取词库

这个类的主要作用,迭代的读取文件,因为路径存在中文,所以必须转码,

同时转码后,由于windows下的路径分隔符,会对编码后的路径进行转义,所以必须先对路径名进行转换


<?php
class Dir
{
	private $fileList=array();
	
	public function __construct($path)
	{
		$this->readFileList($path);
	}

	function readFileList($path)
	{
		$path=$this->transPathSep($path);
		$encode=mb_detect_encoding($path, array('GB2312','GBK','UTF-8','BIG5','LATIN1'));
		$path=mb_convert_encoding($path, 'GB2312', $encode);
		//用于路径读取时用UTF编码会失败,所以先转成GB2312
		if ($fd=opendir($path))
		{
			while($fileName=readdir($fd))
			{
				//如果不是当前目录和上级目录
				if($fileName !="." && $fileName !="..")
				{
					//如果是一个文件
					if(is_file($path.'/'.$fileName))
					{	
						$extName=pathinfo($path."/".$fileName)["extension"];
						if(strtolower($extName)=='txt')
						{
							//上面把路径转成了GB2312,这里再转换会UTF-8编码
							$temp=mb_convert_encoding($path.'/'.$fileName, 'UTF-8', $encode);
							$groupName=$this->groupFile($temp);
							$this->fileList[$groupName][]=$temp;
						}
					}
					//如果是一个目录,则继续递归读取
					else if(is_dir($path.'/'.$fileName))
					{
						$this->readFileList($path.'/'.$fileName);
					}
				}	
			
			}

		}
		@closedir($fd);
		
	}
	
	public function getFileList()
	{
		return $this->fileList;
	}
	//提取单词分类,比如从A-Z
	private function groupFile($filename)
	{
		$pos=strripos($filename, '/');
		$word=strtolower(substr($filename, $pos+1, 1));
		return $word;
	}
	//转换window环境下路径的默认分隔符\为PHP识别更好的/
	//因为路径名中包含汉字时,必须转换为gb2312时,php才能识别
	//而在转换为gb2312后,如果路径名是以windows下的\分隔的,则被转换为gb2312的中文会被转义
	//最后就会导致读取对应的路径失败
	//******所以在{路径名}中包含中文时,一定要先转换路径分隔符,然后转换为gb2312编码
	private function transPathSep($path)
	{
		$system=$_SERVER["SERVER_SOFTWARE"];
		$pat="#\((.*?)\)#";
		$sysVer=null;
		if(preg_match($pat,$system,$match))
		{
			$sysVer=$match[1];
		}
		else
		{
			die("匹配系统类型失败<br />");
		}
		if(strtolower($sysVer)=="win32")
		{
			$realPath=str_replace("\\","/",$path);
			return $realPath;
		}
	}
	
}
/* 
$dir=new Dir('E:\CodeEdit\php\ciba\TXT格式的牛津电子词典\牛津电子词典');
$list=$dir->getFileList();
echo "<pre>";
print_r($list); 
echo "</pre>";  */

?>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值