国内流行的内容管理系统(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.

1125 lines
38KB

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