国内流行的内容管理系统(CMS)多端全媒体解决方案 https://www.dedebiz.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1048 lines
37KB

  1. <?php
  2. if (!defined('DEDEINC')) exit('dedebiz');
  3. /**
  4. * Unicode编码词典的php分词器
  5. *
  6. * 1、只适用于php5,必要函数 iconv
  7. * 2、本程序是使用RMM逆向匹配算法进行分词的,词库需要特别编译,本类里提供了 MakeDict() 方法
  8. * 3、简单操作流程:SetSource -> StartAnalysis -> Get***Result
  9. * 4、对主词典使用特殊格式进行编码, 不需要载入词典到内存操作
  10. *
  11. * @version $Id: splitword.class.php 2 11:45 2011-2-14 itplato $
  12. * @package DedeBIZ.Libraries
  13. * @copyright Copyright (c) 2022, DedeBIZ.COM
  14. * @license https://www.dedebiz.com/license
  15. * @link https://www.dedebiz.com
  16. */
  17. //常量定义
  18. define('_SP_', chr(0xFF).chr(0xFE));
  19. define('UCS2', 'ucs-2be');
  20. class SplitWord
  21. {
  22. //hash算法选项
  23. var $mask_value = 0xFFFF;
  24. //输入和输出的字符编码(只允许 utf-8、gbk/gb2312/gb18030、big5 三种类型)
  25. var $sourceCharSet = 'utf-8';
  26. var $targetCharSet = 'utf-8';
  27. //生成的分词结果数据类型 1 为全部, 2为 词典词汇及单个中日韩简繁字符及英文, 3 为词典词汇及英文
  28. var $resultType = 1;
  29. //句子长度小于这个数值时不拆分,notSplitLen = n(个汉字) * 2 + 1
  30. var $notSplitLen = 5;
  31. //把英文单词全部转小写
  32. var $toLower = FALSE;
  33. //使用最大切分模式对二元词进行消岐
  34. var $differMax = FALSE;
  35. //尝试合并单字
  36. var $unitWord = TRUE;
  37. //初始化类时直接加载词典
  38. var $loadInit = TRUE;
  39. //使用热门词优先模式进行消岐
  40. var $differFreq = FALSE;
  41. //被转换为unicode的源字符串
  42. var $sourceString = '';
  43. //附加词典
  44. var $addonDic = array();
  45. var $addonDicFile = 'data/words_addons.dic';
  46. //主词典
  47. var $dicStr = '';
  48. var $mainDic = array();
  49. var $mainDicHand = FALSE;
  50. var $mainDicInfos = array();
  51. var $mainDicFile = 'data/base_dic_full.dic';
  52. //是否直接载入词典(选是载入速度较慢,但解析较快;选否载入较快,但解析较慢,需要时才会载入特定的词条)
  53. var $mainDicFileZip = 'data/base_dic_full.zip';
  54. var $isLoadAll = FALSE;
  55. var $isUnpacked = FALSE;
  56. //主词典词语最大长度 x / 2
  57. var $dicWordMax = 14;
  58. //粗分后的数组(通常是截取句子等用途)
  59. var $simpleResult = array();
  60. //最终结果(用空格分开的词汇列表)
  61. var $finallyResult = '';
  62. //是否已经载入词典
  63. var $isLoadDic = FALSE;
  64. //系统识别或合并的新词
  65. var $newWords = array();
  66. var $foundWordStr = '';
  67. //词库载入时间
  68. var $loadTime = 0;
  69. /**
  70. * 构造函数
  71. * @param $source_charset
  72. * @param $target_charset
  73. * @param $load_alldic
  74. * @param $source
  75. *
  76. * @return void
  77. */
  78. function __construct($source_charset='utf-8', $target_charset='utf-8', $load_all=TRUE, $source='')
  79. {
  80. $this->SetSource( $source, $source_charset, $target_charset );
  81. $this->isLoadAll = $load_all;
  82. if(file_exists(DEDEINC.'/'.$this->mainDicFile)) $this->isUnpacked = TRUE;
  83. if($this->loadInit) $this->LoadDict();
  84. }
  85. function SplitWord($source_charset='utf-8', $target_charset='utf-8', $load_all=TRUE, $source='')
  86. {
  87. $this->__construct($source_charset, $target_charset, $load_all, $source);
  88. }
  89. /**
  90. * 析构函数
  91. */
  92. function __destruct()
  93. {
  94. if( $this->mainDicHand !== FALSE )
  95. {
  96. @fclose( $this->mainDicHand );
  97. }
  98. }
  99. /**
  100. * 根据字符串计算key索引
  101. * @param $key
  102. * @return short int
  103. */
  104. function _get_index( $key )
  105. {
  106. $l = strlen($key);
  107. $h = 0x238f13af;
  108. while ($l--)
  109. {
  110. $h += ($h << 5);
  111. $h ^= ord($key[$l]);
  112. $h &= 0x7fffffff;
  113. }
  114. return ($h % $this->mask_value);
  115. }
  116. /**
  117. * 从文件获得词
  118. * @param $key
  119. * @param $type (类型 word 或 key_groups)
  120. * @return short int
  121. */
  122. function GetWordInfos( $key, $type='word' )
  123. {
  124. if( !$this->mainDicHand )
  125. {
  126. $this->mainDicHand = fopen($this->mainDicFile, 'r');
  127. }
  128. $p = 0;
  129. $keynum = $this->_get_index( $key );
  130. if( isset($this->mainDicInfos[ $keynum ]) )
  131. {
  132. $data = $this->mainDicInfos[ $keynum ];
  133. } else {
  134. //rewind( $this->mainDicHand );
  135. $move_pos = $keynum * 8;
  136. fseek($this->mainDicHand, $move_pos, SEEK_SET);
  137. $dat = fread($this->mainDicHand, 8);
  138. $arr = unpack('I1s/n1l/n1c', $dat);
  139. if( $arr['l'] == 0 )
  140. {
  141. return FALSE;
  142. }
  143. fseek($this->mainDicHand, $arr['s'], SEEK_SET);
  144. $data = @unserialize(fread($this->mainDicHand, $arr['l']));
  145. $this->mainDicInfos[ $keynum ] = $data;
  146. }
  147. if( !is_array($data) || !isset($data[$key]) )
  148. {
  149. return FALSE;
  150. }
  151. return ($type=='word' ? $data[$key] : $data);
  152. }
  153. /**
  154. * 设置源字符串
  155. * @param $source
  156. * @param $source_charset
  157. * @param $target_charset
  158. *
  159. * @return bool
  160. */
  161. function SetSource( $source, $source_charset='utf-8', $target_charset='utf-8' )
  162. {
  163. $this->sourceCharSet = strtolower($source_charset);
  164. $this->targetCharSet = strtolower($target_charset);
  165. $this->simpleResult = array();
  166. $this->finallyResult = array();
  167. $this->finallyIndex = array();
  168. if( $source != '' )
  169. {
  170. $rs = TRUE;
  171. if( preg_match("/^utf/", $source_charset) ) {
  172. $this->sourceString = @iconv('utf-8', UCS2, $source);
  173. }
  174. else if( preg_match("/^gb/", $source_charset) ) {
  175. $this->sourceString = @iconv('utf-8', UCS2, iconv('gb18030', 'utf-8', $source));
  176. }
  177. else if( preg_match("/^big/", $source_charset) ) {
  178. $this->sourceString = @iconv('utf-8', UCS2, iconv('big5', 'utf-8', $source));
  179. } else {
  180. $rs = FALSE;
  181. }
  182. } else {
  183. $rs = FALSE;
  184. }
  185. return $rs;
  186. }
  187. /**
  188. * 设置结果类型(只在获取finallyResult才有效)
  189. * @param $rstype 1 为全部, 2去除特殊符号
  190. *
  191. * @return void
  192. */
  193. function SetResultType( $rstype )
  194. {
  195. $this->resultType = $rstype;
  196. }
  197. /**
  198. * 载入词典
  199. *
  200. * @return void
  201. */
  202. function LoadDict( $maindic='' )
  203. {
  204. $this->addonDicFile = DEDEINC.'/'.$this->addonDicFile;
  205. $this->mainDicFile = DEDEINC.'/'.$this->mainDicFile;
  206. $this->mainDicFileZip = DEDEINC.'/'.$this->mainDicFileZip;
  207. $startt = microtime(TRUE);
  208. //正常读取文件
  209. $dicAddon = $this->addonDicFile;
  210. if($maindic=='' || !file_exists($maindic) )
  211. {
  212. $dicWords = $this->mainDicFile ;
  213. } else {
  214. $dicWords = $maindic;
  215. $this->mainDicFile = $maindic;
  216. }
  217. //加载主词典(只打开)
  218. if($this->isUnpacked){
  219. $this->mainDicHand = fopen($dicWords, 'r');
  220. } else {
  221. $this->InportDict($this->mainDicFileZip);
  222. }
  223. //载入副词典
  224. $hw = '';
  225. $ds = file($dicAddon);
  226. foreach($ds as $d)
  227. {
  228. $d = trim($d);
  229. if($d=='') continue;
  230. $estr = substr($d, 1, 1);
  231. if( $estr==':' ) {
  232. $hw = substr($d, 0, 1);
  233. } else {
  234. $spstr = _SP_;
  235. $spstr = iconv(UCS2, 'utf-8', $spstr);
  236. $ws = explode(',', $d);
  237. $wall = iconv('utf-8', UCS2, join($spstr, $ws));
  238. $ws = explode(_SP_, $wall);
  239. foreach($ws as $estr)
  240. {
  241. $this->addonDic[$hw][$estr] = strlen($estr);
  242. }
  243. }
  244. }
  245. $this->loadTime = microtime(TRUE) - $startt;
  246. $this->isLoadDic = TRUE;
  247. }
  248. /**
  249. * 检测某个词是否存在
  250. */
  251. function IsWord( $word )
  252. {
  253. $winfos = $this->GetWordInfos( $word );
  254. return ($winfos !== FALSE);
  255. }
  256. /**
  257. * 获得某个词的词性及词频信息
  258. * @parem $word unicode编码的词
  259. * @return void
  260. */
  261. function GetWordProperty($word)
  262. {
  263. if( strlen($word)<4 )
  264. {
  265. return '/s';
  266. }
  267. $infos = $this->GetWordInfos($word);
  268. return isset($infos[1]) ? "/{$infos[1]}{$infos[0]}" : "/s";
  269. }
  270. /**
  271. * 指定某词的词性信息(通常是新词)
  272. * @parem $word unicode编码的词
  273. * @parem $infos array('c' => 词频, 'm' => 词性);
  274. * @return void;
  275. */
  276. function SetWordInfos($word, $infos)
  277. {
  278. if( strlen($word)<4 )
  279. {
  280. return ;
  281. }
  282. if( isset($this->mainDicInfos[$word]) )
  283. {
  284. $this->newWords[$word]++;
  285. $this->mainDicInfos[$word]['c']++;
  286. } else {
  287. $this->newWords[$word] = 1;
  288. $this->mainDicInfos[$word] = $infos;
  289. }
  290. }
  291. /**
  292. * 开始执行分析
  293. * @parem bool optimize 是否对结果进行优化
  294. * @return bool
  295. */
  296. function StartAnalysis($optimize=TRUE)
  297. {
  298. if( !$this->isLoadDic )
  299. {
  300. $this->LoadDict();
  301. }
  302. $this->simpleResult = $this->finallyResult = array();
  303. $this->sourceString .= chr(0).chr(32);
  304. $slen = strlen($this->sourceString);
  305. $sbcArr = array();
  306. $j = 0;
  307. //全角与半角字符对照表
  308. for($i=0xFF00; $i < 0xFF5F; $i++)
  309. {
  310. $scb = 0x20 + $j;
  311. $j++;
  312. $sbcArr[$i] = $scb;
  313. }
  314. //对字符串进行粗分
  315. $onstr = '';
  316. $lastc = 1; //1 中/韩/日文, 2 英文/数字/符号('.', '@', '#', '+'), 3 ANSI符号 4 纯数字 5 非ANSI符号或不支持字符
  317. $s = 0;
  318. $ansiWordMatch = "[0-9a-z@#%\+\.-]";
  319. $notNumberMatch = "[a-z@#%\+]";
  320. for($i=0; $i < $slen; $i++)
  321. {
  322. $c = $this->sourceString[$i].$this->sourceString[++$i];
  323. $cn = hexdec(bin2hex($c));
  324. $cn = isset($sbcArr[$cn]) ? $sbcArr[$cn] : $cn;
  325. //ANSI字符
  326. if($cn < 0x80)
  327. {
  328. if( preg_match('/'.$ansiWordMatch.'/i', chr($cn)) )
  329. {
  330. if( $lastc != 2 && $onstr != '') {
  331. $this->simpleResult[$s]['w'] = $onstr;
  332. $this->simpleResult[$s]['t'] = $lastc;
  333. $this->_deep_analysis($onstr, $lastc, $s, $optimize);
  334. $s++;
  335. $onstr = '';
  336. }
  337. $lastc = 2;
  338. $onstr .= chr(0).chr($cn);
  339. } else {
  340. if( $onstr != '' )
  341. {
  342. $this->simpleResult[$s]['w'] = $onstr;
  343. if( $lastc==2 )
  344. {
  345. if( !preg_match('/'.$notNumberMatch.'/i', iconv(UCS2, 'utf-8', $onstr)) ) $lastc = 4;
  346. }
  347. $this->simpleResult[$s]['t'] = $lastc;
  348. if( $lastc != 4 ) $this->_deep_analysis($onstr, $lastc, $s, $optimize);
  349. $s++;
  350. }
  351. $onstr = '';
  352. $lastc = 3;
  353. if($cn < 31)
  354. {
  355. continue;
  356. } else {
  357. $this->simpleResult[$s]['w'] = chr(0).chr($cn);
  358. $this->simpleResult[$s]['t'] = 3;
  359. $s++;
  360. }
  361. }
  362. }
  363. //普通字符
  364. else
  365. {
  366. //正常文字
  367. if( ($cn>0x3FFF && $cn < 0x9FA6) || ($cn>0xF8FF && $cn < 0xFA2D)
  368. || ($cn>0xABFF && $cn < 0xD7A4) || ($cn>0x3040 && $cn < 0x312B) )
  369. {
  370. if( $lastc != 1 && $onstr != '')
  371. {
  372. $this->simpleResult[$s]['w'] = $onstr;
  373. if( $lastc==2 )
  374. {
  375. if( !preg_match('/'.$notNumberMatch.'/i', iconv(UCS2, 'utf-8', $onstr)) ) $lastc = 4;
  376. }
  377. $this->simpleResult[$s]['t'] = $lastc;
  378. if( $lastc != 4 ) $this->_deep_analysis($onstr, $lastc, $s, $optimize);
  379. $s++;
  380. $onstr = '';
  381. }
  382. $lastc = 1;
  383. $onstr .= $c;
  384. }
  385. //特殊符号
  386. else
  387. {
  388. if( $onstr != '' )
  389. {
  390. $this->simpleResult[$s]['w'] = $onstr;
  391. if( $lastc==2 )
  392. {
  393. if( !preg_match('/'.$notNumberMatch.'/i', iconv(UCS2, 'utf-8', $onstr)) ) $lastc = 4;
  394. }
  395. $this->simpleResult[$s]['t'] = $lastc;
  396. if( $lastc != 4 ) $this->_deep_analysis($onstr, $lastc, $s, $optimize);
  397. $s++;
  398. }
  399. //检测书名
  400. if( $cn == 0x300A )
  401. {
  402. $tmpw = '';
  403. $n = 1;
  404. $isok = FALSE;
  405. $ew = chr(0x30).chr(0x0B);
  406. while(TRUE)
  407. {
  408. if(!isset($this->sourceString[$i+$n]) && !isset($this->sourceString[$i+$n+1]))
  409. break;
  410. $w = $this->sourceString[$i+$n].$this->sourceString[$i+$n+1];
  411. if( $w == $ew )
  412. {
  413. $this->simpleResult[$s]['w'] = $c;
  414. $this->simpleResult[$s]['t'] = 5;
  415. $s++;
  416. $this->simpleResult[$s]['w'] = $tmpw;
  417. $this->newWords[$tmpw] = 1;
  418. if( !isset($this->newWords[$tmpw]) )
  419. {
  420. $this->foundWordStr .= $this->_out_string_encoding($tmpw).'/nb, ';
  421. $this->SetWordInfos($tmpw, array('c'=>1, 'm'=>'nb'));
  422. }
  423. $this->simpleResult[$s]['t'] = 13;
  424. $s++;
  425. //最大切分模式对书名继续分词
  426. if( $this->differMax )
  427. {
  428. $this->simpleResult[$s]['w'] = $tmpw;
  429. $this->simpleResult[$s]['t'] = 21;
  430. $this->_deep_analysis($tmpw, $lastc, $s, $optimize);
  431. $s++;
  432. }
  433. $this->simpleResult[$s]['w'] = $ew;
  434. $this->simpleResult[$s]['t'] = 5;
  435. $s++;
  436. $i = $i + $n + 1;
  437. $isok = TRUE;
  438. $onstr = '';
  439. $lastc = 5;
  440. break;
  441. } else {
  442. $n = $n+2;
  443. $tmpw .= $w;
  444. if( strlen($tmpw) > 60 )
  445. {
  446. break;
  447. }
  448. }
  449. }//while
  450. if( !$isok )
  451. {
  452. $this->simpleResult[$s]['w'] = $c;
  453. $this->simpleResult[$s]['t'] = 5;
  454. $s++;
  455. $onstr = '';
  456. $lastc = 5;
  457. }
  458. continue;
  459. }
  460. $onstr = '';
  461. $lastc = 5;
  462. if( $cn==0x3000 )
  463. {
  464. continue;
  465. } else {
  466. $this->simpleResult[$s]['w'] = $c;
  467. $this->simpleResult[$s]['t'] = 5;
  468. $s++;
  469. }
  470. }//2byte symbol
  471. }//end 2byte char
  472. }//end for
  473. //处理分词后的结果
  474. $this->_sort_finally_result();
  475. }
  476. /**
  477. * 深入分词
  478. * @parem $str
  479. * @parem $ctype (2 英文类, 3 中/韩/日文类)
  480. * @parem $spos 当前粗分结果游标
  481. * @return bool
  482. */
  483. function _deep_analysis( &$str, $ctype, $spos, $optimize=TRUE )
  484. {
  485. //中文句子
  486. if( $ctype==1 )
  487. {
  488. $slen = strlen($str);
  489. //小于系统配置分词要求长度的句子
  490. if( $slen < $this->notSplitLen )
  491. {
  492. $tmpstr = '';
  493. $lastType = 0;
  494. if( $spos > 0 ) $lastType = $this->simpleResult[$spos-1]['t'];
  495. if($slen < 5)
  496. {
  497. //echo iconv(UCS2, 'utf-8', $str).'<br>';
  498. if( $lastType==4 && ( isset($this->addonDic['u'][$str]) || isset($this->addonDic['u'][substr($str, 0, 2)]) ) )
  499. {
  500. $str2 = '';
  501. if( !isset($this->addonDic['u'][$str]) && isset($this->addonDic['s'][substr($str, 2, 2)]) )
  502. {
  503. $str2 = substr($str, 2, 2);
  504. $str = substr($str, 0, 2);
  505. }
  506. $ww = $this->simpleResult[$spos - 1]['w'].$str;
  507. $this->simpleResult[$spos - 1]['w'] = $ww;
  508. $this->simpleResult[$spos - 1]['t'] = 4;
  509. if( !isset($this->newWords[$this->simpleResult[$spos - 1]['w']]) )
  510. {
  511. $this->foundWordStr .= $this->_out_string_encoding( $ww ).'/mu, ';
  512. $this->SetWordInfos($ww, array('c'=>1, 'm'=>'mu'));
  513. }
  514. $this->simpleResult[$spos]['w'] = '';
  515. if( $str2 != '' )
  516. {
  517. $this->finallyResult[$spos-1][] = $ww;
  518. $this->finallyResult[$spos-1][] = $str2;
  519. }
  520. } else {
  521. $this->finallyResult[$spos][] = $str;
  522. }
  523. } else {
  524. $this->_deep_analysis_cn( $str, $ctype, $spos, $slen, $optimize );
  525. }
  526. }
  527. //正常长度的句子,循环进行分词处理
  528. else {
  529. $this->_deep_analysis_cn( $str, $ctype, $spos, $slen, $optimize );
  530. }
  531. }
  532. //英文句子,转为小写
  533. else {
  534. if( $this->toLower ) {
  535. $this->finallyResult[$spos][] = strtolower($str);
  536. } else {
  537. $this->finallyResult[$spos][] = $str;
  538. }
  539. }
  540. }
  541. /**
  542. * 中文的深入分词
  543. * @parem $str
  544. * @return void
  545. */
  546. function _deep_analysis_cn( &$str, $lastec, $spos, $slen, $optimize=TRUE )
  547. {
  548. $quote1 = chr(0x20).chr(0x1C);
  549. $tmparr = array();
  550. $hasw = 0;
  551. //如果前一个词为 “ , 并且字符串小于3个字符当成一个词处理
  552. if( $spos > 0 && $slen < 11 && $this->simpleResult[$spos-1]['w']==$quote1 )
  553. {
  554. $tmparr[] = $str;
  555. if( !isset($this->newWords[$str]) )
  556. {
  557. $this->foundWordStr .= $this->_out_string_encoding($str).'/nq, ';
  558. $this->SetWordInfos($str, array('c'=>1, 'm'=>'nq'));
  559. }
  560. if( !$this->differMax )
  561. {
  562. $this->finallyResult[$spos][] = $str;
  563. return ;
  564. }
  565. }
  566. //进行切分
  567. for($i=$slen-1; $i > 0; $i -= 2)
  568. {
  569. //单个词
  570. $nc = $str[$i-1].$str[$i];
  571. //是否已经到最后两个字
  572. if( $i <= 2 )
  573. {
  574. $tmparr[] = $nc;
  575. $i = 0;
  576. break;
  577. }
  578. $isok = FALSE;
  579. $i = $i + 1;
  580. for($k=$this->dicWordMax; $k>1; $k=$k-2)
  581. {
  582. if($i < $k) continue;
  583. $w = substr($str, $i-$k, $k);
  584. if( strlen($w) <= 2 )
  585. {
  586. $i = $i - 1;
  587. break;
  588. }
  589. if( $this->IsWord( $w ) )
  590. {
  591. $tmparr[] = $w;
  592. $i = $i - $k + 1;
  593. $isok = TRUE;
  594. break;
  595. }
  596. }
  597. //echo '<hr />';
  598. //没适合词
  599. if(!$isok) $tmparr[] = $nc;
  600. }
  601. $wcount = count($tmparr);
  602. if( $wcount==0 ) return ;
  603. $this->finallyResult[$spos] = array_reverse($tmparr);
  604. //优化结果(岐义处理、新词、数词、人名识别等)
  605. if( $optimize )
  606. {
  607. $this->_optimize_result( $this->finallyResult[$spos], $spos );
  608. }
  609. }
  610. /**
  611. * 对最终分词结果进行优化(把simpleresult结果合并,并尝试新词识别、数词合并等)
  612. * @parem $optimize 是否优化合并的结果
  613. * @return bool
  614. */
  615. //t = 1 中/韩/日文, 2 英文/数字/符号('.', '@', '#', '+'), 3 ANSI符号 4 纯数字 5 非ANSI符号或不支持字符
  616. function _optimize_result( &$smarr, $spos )
  617. {
  618. $newarr = array();
  619. $prePos = $spos - 1;
  620. $arlen = count($smarr);
  621. $i = $j = 0;
  622. //检测数量词
  623. if( $prePos > -1 && !isset($this->finallyResult[$prePos]) )
  624. {
  625. $lastw = $this->simpleResult[$prePos]['w'];
  626. $lastt = $this->simpleResult[$prePos]['t'];
  627. if( ($lastt==4 || isset( $this->addonDic['c'][$lastw] )) && isset( $this->addonDic['u'][$smarr[0]] ) )
  628. {
  629. $this->simpleResult[$prePos]['w'] = $lastw.$smarr[0];
  630. $this->simpleResult[$prePos]['t'] = 4;
  631. if( !isset($this->newWords[ $this->simpleResult[$prePos]['w'] ]) )
  632. {
  633. $this->foundWordStr .= $this->_out_string_encoding( $this->simpleResult[$prePos]['w'] ).'/mu, ';
  634. $this->SetWordInfos($this->simpleResult[$prePos]['w'], array('c'=>1, 'm'=>'mu'));
  635. }
  636. $smarr[0] = '';
  637. $i++;
  638. }
  639. }
  640. for(; $i < $arlen; $i++)
  641. {
  642. if( !isset( $smarr[$i+1] ) )
  643. {
  644. $newarr[$j] = $smarr[$i];
  645. break;
  646. }
  647. $cw = $smarr[$i];
  648. $nw = $smarr[$i+1];
  649. $ischeck = FALSE;
  650. //检测数量词
  651. if( isset( $this->addonDic['c'][$cw] ) && isset( $this->addonDic['u'][$nw] ) )
  652. {
  653. //最大切分时保留合并前的词
  654. if($this->differMax)
  655. {
  656. $newarr[$j] = chr(0).chr(0x28);
  657. $j++;
  658. $newarr[$j] = $cw;
  659. $j++;
  660. $newarr[$j] = $nw;
  661. $j++;
  662. $newarr[$j] = chr(0).chr(0x29);
  663. $j++;
  664. }
  665. $newarr[$j] = $cw.$nw;
  666. if( !isset($this->newWords[$newarr[$j]]) )
  667. {
  668. $this->foundWordStr .= $this->_out_string_encoding( $newarr[$j] ).'/mu, ';
  669. $this->SetWordInfos($newarr[$j], array('c'=>1, 'm'=>'mu'));
  670. }
  671. $j++; $i++; $ischeck = TRUE;
  672. }
  673. //检测前导词(通常是姓)
  674. else if( isset( $this->addonDic['n'][ $smarr[$i] ] ) )
  675. {
  676. $is_rs = FALSE;
  677. //词语是副词或介词或频率很高的词不作为人名
  678. if( strlen($nw)==4 )
  679. {
  680. $winfos = $this->GetWordInfos($nw);
  681. if(isset($winfos['m']) && ($winfos['m']=='r' || $winfos['m']=='c' || $winfos['c']>500) )
  682. {
  683. $is_rs = TRUE;
  684. }
  685. }
  686. if( !isset($this->addonDic['s'][$nw]) && strlen($nw)<5 && !$is_rs )
  687. {
  688. $newarr[$j] = $cw.$nw;
  689. //echo iconv(UCS2, 'utf-8', $newarr[$j])."<br>";
  690. //尝试检测第三个词
  691. if( strlen($nw)==2 && isset($smarr[$i+2]) && strlen($smarr[$i+2])==2 && !isset( $this->addonDic['s'][$smarr[$i+2]] ) )
  692. {
  693. $newarr[$j] .= $smarr[$i+2];
  694. $i++;
  695. }
  696. if( !isset($this->newWords[$newarr[$j]]) )
  697. {
  698. $this->SetWordInfos($newarr[$j], array('c'=>1, 'm'=>'nr'));
  699. $this->foundWordStr .= $this->_out_string_encoding($newarr[$j]).'/nr, ';
  700. }
  701. //为了防止错误,保留合并前的姓名
  702. if(strlen($nw)==4)
  703. {
  704. $j++;
  705. $newarr[$j] = chr(0).chr(0x28);
  706. $j++;
  707. $newarr[$j] = $cw;
  708. $j++;
  709. $newarr[$j] = $nw;
  710. $j++;
  711. $newarr[$j] = chr(0).chr(0x29);
  712. }
  713. $j++; $i++; $ischeck = TRUE;
  714. }
  715. }
  716. //检测后缀词(地名等)
  717. else if( isset($this->addonDic['a'][$nw]) )
  718. {
  719. $is_rs = FALSE;
  720. //词语是副词或介词不作为前缀
  721. if( strlen($cw)>2 )
  722. {
  723. $winfos = $this->GetWordInfos($cw);
  724. if(isset($winfos['m']) && ($winfos['m']=='a' || $winfos['m']=='r' || $winfos['m']=='c' || $winfos['c']>500) )
  725. {
  726. $is_rs = TRUE;
  727. }
  728. }
  729. if( !isset($this->addonDic['s'][$cw]) && !$is_rs )
  730. {
  731. $newarr[$j] = $cw.$nw;
  732. if( !isset($this->newWords[$newarr[$j]]) )
  733. {
  734. $this->foundWordStr .= $this->_out_string_encoding($newarr[$j]).'/na, ';
  735. $this->SetWordInfos($newarr[$j], array('c'=>1, 'm'=>'na'));
  736. }
  737. $i++; $j++; $ischeck = TRUE;
  738. }
  739. }
  740. //新词识别(暂无规则)
  741. else if($this->unitWord)
  742. {
  743. if(strlen($cw)==2 && strlen($nw)==2
  744. && !isset($this->addonDic['s'][$cw]) && !isset($this->addonDic['t'][$cw]) && !isset($this->addonDic['a'][$cw])
  745. && !isset($this->addonDic['s'][$nw]) && !isset($this->addonDic['c'][$nw]))
  746. {
  747. $newarr[$j] = $cw.$nw;
  748. //尝试检测第三个词
  749. if( isset($smarr[$i+2]) && strlen($smarr[$i+2])==2 && (isset( $this->addonDic['a'][$smarr[$i+2]] ) || isset( $this->addonDic['u'][$smarr[$i+2]] )) )
  750. {
  751. $newarr[$j] .= $smarr[$i+2];
  752. $i++;
  753. }
  754. if( !isset($this->newWords[$newarr[$j]]) )
  755. {
  756. $this->foundWordStr .= $this->_out_string_encoding($newarr[$j]).'/ms, ';
  757. $this->SetWordInfos($newarr[$j], array('c'=>1, 'm'=>'ms'));
  758. }
  759. $i++; $j++; $ischeck = TRUE;
  760. }
  761. }
  762. //不符合规则
  763. if( !$ischeck )
  764. {
  765. $newarr[$j] = $cw;
  766. //二元消岐处理——最大切分模式
  767. if( $this->differMax && !isset($this->addonDic['s'][$cw]) && strlen($cw) < 5 && strlen($nw) < 7)
  768. {
  769. $slen = strlen($nw);
  770. $hasDiff = FALSE;
  771. for($y=2; $y <= $slen-2; $y=$y+2)
  772. {
  773. $nhead = substr($nw, $y-2, 2);
  774. $nfont = $cw.substr($nw, 0, $y-2);
  775. if( $this->IsWord( $nfont.$nhead ) )
  776. {
  777. if( strlen($cw) > 2 ) $j++;
  778. $hasDiff = TRUE;
  779. $newarr[$j] = $nfont.$nhead;
  780. }
  781. }
  782. }
  783. $j++;
  784. }
  785. }//end for
  786. $smarr = $newarr;
  787. }
  788. /**
  789. * 转换最终分词结果到 finallyResult 数组
  790. * @return void
  791. */
  792. function _sort_finally_result()
  793. {
  794. $newarr = array();
  795. $i = 0;
  796. foreach($this->simpleResult as $k=>$v)
  797. {
  798. if( empty($v['w']) ) continue;
  799. if( isset($this->finallyResult[$k]) && count($this->finallyResult[$k]) > 0 )
  800. {
  801. foreach($this->finallyResult[$k] as $w)
  802. {
  803. if(!empty($w))
  804. {
  805. $newarr[$i]['w'] = $w;
  806. $newarr[$i]['t'] = 20;
  807. $i++;
  808. }
  809. }
  810. }
  811. else if($v['t'] != 21)
  812. {
  813. $newarr[$i]['w'] = $v['w'];
  814. $newarr[$i]['t'] = $v['t'];
  815. $i++;
  816. }
  817. }
  818. $this->finallyResult = $newarr;
  819. $newarr = '';
  820. }
  821. /**
  822. * 把uncode字符串转换为输出字符串
  823. * @parem str
  824. * return string
  825. */
  826. function _out_string_encoding( &$str )
  827. {
  828. $rsc = $this->_source_result_charset();
  829. if( $rsc==1 ) {
  830. $rsstr = iconv(UCS2, 'utf-8', $str);
  831. }
  832. else if( $rsc==2 ) {
  833. $rsstr = iconv('utf-8', 'gb18030', iconv(UCS2, 'utf-8', $str) );
  834. } else {
  835. $rsstr = iconv('utf-8', 'big5', iconv(UCS2, 'utf-8', $str) );
  836. }
  837. return $rsstr;
  838. }
  839. /**
  840. * 获取最终结果字符串(用空格分开后的分词结果)
  841. * @return string
  842. */
  843. function GetFinallyResult($spword=' ', $word_meanings=FALSE)
  844. {
  845. $rsstr = '';
  846. foreach($this->finallyResult as $v)
  847. {
  848. if( $this->resultType==2 && ($v['t']==3 || $v['t']==5) )
  849. {
  850. continue;
  851. }
  852. $m = '';
  853. if( $word_meanings )
  854. {
  855. $m = $this->GetWordProperty($v['w']);
  856. }
  857. $w = $this->_out_string_encoding($v['w']);
  858. if( $w != ' ' )
  859. {
  860. if($word_meanings) {
  861. $rsstr .= $spword.$w.$m;
  862. } else {
  863. $rsstr .= $spword.$w;
  864. }
  865. }
  866. }
  867. return $rsstr;
  868. }
  869. /**
  870. * 获取粗分结果,不包含粗分属性
  871. * @return array()
  872. */
  873. function GetSimpleResult()
  874. {
  875. $rearr = array();
  876. foreach($this->simpleResult as $k=>$v)
  877. {
  878. if( empty($v['w']) ) continue;
  879. $w = $this->_out_string_encoding($v['w']);
  880. if( $w != ' ' ) $rearr[] = $w;
  881. }
  882. return $rearr;
  883. }
  884. /**
  885. * 获取粗分结果,包含粗分属性(1中文词句、2 ANSI词汇(包括全角),3 ANSI标点符号(包括全角),4数字(包括全角),5 中文标点或无法识别字符)
  886. * @return array()
  887. */
  888. function GetSimpleResultAll()
  889. {
  890. $rearr = array();
  891. foreach($this->simpleResult as $k=>$v)
  892. {
  893. $w = $this->_out_string_encoding($v['w']);
  894. if( $w != ' ' )
  895. {
  896. $rearr[$k]['w'] = $w;
  897. $rearr[$k]['t'] = $v['t'];
  898. }
  899. }
  900. return $rearr;
  901. }
  902. /**
  903. * 获取索引hash数组
  904. * @return array('word'=>count,)
  905. */
  906. function GetFinallyIndex()
  907. {
  908. $rearr = array();
  909. foreach($this->finallyResult as $v)
  910. {
  911. if( $this->resultType==2 && ($v['t']==3 || $v['t']==5) )
  912. {
  913. continue;
  914. }
  915. $w = $this->_out_string_encoding($v['w']);
  916. if( $w == ' ' )
  917. {
  918. continue;
  919. }
  920. if( isset($rearr[$w]) )
  921. {
  922. $rearr[$w]++;
  923. } else {
  924. $rearr[$w] = 1;
  925. }
  926. }
  927. return $rearr;
  928. }
  929. /**
  930. * 获得保存目标编码
  931. * @return int
  932. */
  933. function _source_result_charset()
  934. {
  935. if( preg_match("/^utf/", $this->targetCharSet) ) {
  936. $rs = 1;
  937. }
  938. else if( preg_match("/^gb/", $this->targetCharSet) ) {
  939. $rs = 2;
  940. }
  941. else if( preg_match("/^big/", $this->targetCharSet) ) {
  942. $rs = 3;
  943. }
  944. else {
  945. $rs = 4;
  946. }
  947. return $rs;
  948. }
  949. /**
  950. * 编译词典
  951. * @parem $sourcefile utf-8编码的文本词典数据文件<参见范例dict/not-build/base_dic_full.txt>
  952. * 注意, 需要PHP开放足够的内存才能完成操作
  953. * @return void
  954. */
  955. function MakeDict( $source_file, $target_file='' )
  956. {
  957. $target_file = ($target_file=='' ? $this->mainDicFile : $target_file);
  958. $allk = array();
  959. $fp = fopen($source_file, 'r');
  960. while( $line = fgets($fp, 512) )
  961. {
  962. if( $line[0]=='@' ) continue;
  963. list($w, $r, $a) = explode(',', $line);
  964. $a = trim( $a );
  965. $w = iconv('utf-8', UCS2, $w);
  966. $k = $this->_get_index( $w );
  967. if( isset($allk[ $k ]) )
  968. $allk[ $k ][ $w ] = array($r, $a);
  969. else
  970. $allk[ $k ][ $w ] = array($r, $a);
  971. }
  972. fclose( $fp );
  973. $fp = fopen($target_file, 'w');
  974. $heade_rarr = array();
  975. $alldat = '';
  976. $start_pos = $this->mask_value * 8;
  977. foreach( $allk as $k => $v )
  978. {
  979. $dat = serialize( $v );
  980. $dlen = strlen($dat);
  981. $alldat .= $dat;
  982. $heade_rarr[ $k ][0] = $start_pos;
  983. $heade_rarr[ $k ][1] = $dlen;
  984. $heade_rarr[ $k ][2] = count( $v );
  985. $start_pos += $dlen;
  986. }
  987. unset( $allk );
  988. for($i=0; $i < $this->mask_value; $i++)
  989. {
  990. if( !isset($heade_rarr[$i]) )
  991. {
  992. $heade_rarr[$i] = array(0, 0, 0);
  993. }
  994. fwrite($fp, pack("Inn", $heade_rarr[$i][0], $heade_rarr[$i][1], $heade_rarr[$i][2]));
  995. }
  996. fwrite( $fp, $alldat);
  997. fclose( $fp );
  998. }
  999. /**
  1000. * 导出词典的词条
  1001. * @parem $targetfile 保存位置
  1002. * @return void
  1003. */
  1004. function ExportDict( $targetfile )
  1005. {
  1006. if( !$this->mainDicHand )
  1007. {
  1008. $this->mainDicHand = fopen($this->mainDicFile, 'rw');
  1009. }
  1010. $fp = fopen($targetfile, 'w');
  1011. for($i=0; $i <= $this->mask_value; $i++)
  1012. {
  1013. $move_pos = $i * 8;
  1014. fseek($this->mainDicHand, $move_pos, SEEK_SET);
  1015. $dat = fread($this->mainDicHand, 8);
  1016. $arr = unpack('I1s/n1l/n1c', $dat);
  1017. if( $arr['l'] == 0 )
  1018. {
  1019. continue;
  1020. }
  1021. fseek($this->mainDicHand, $arr['s'], SEEK_SET);
  1022. $data = @unserialize(fread($this->mainDicHand, $arr['l']));
  1023. if( !is_array($data) ) continue;
  1024. foreach($data as $k => $v)
  1025. {
  1026. $w = iconv(UCS2, 'utf-8', $k);
  1027. fwrite($fp, "{$w},{$v[0]},{$v[1]}\n");
  1028. }
  1029. }
  1030. fclose( $fp );
  1031. return TRUE;
  1032. }
  1033. function InportDict( $targetfile )
  1034. {
  1035. if(!ini_set('memory_limit', '128M'))
  1036. exit('设置内存错误,请到官网下载解压版的base_dic_full.dic!');
  1037. require_once(DEDEINC.'/libraries/zip.class.php');
  1038. $zip = new zip();
  1039. //echo $targetfile;
  1040. $unpackagefile = array_keys($zip->Extract($targetfile,DEDEINC.'/data/'));
  1041. //exit();
  1042. $this->MakeDict(DEDEINC.'/data/'.$unpackagefile[0]);
  1043. unlink(DEDEINC.'/data/'.$unpackagefile[0]);
  1044. return true;
  1045. }
  1046. }