php简单分词,php简单中文分词系统(1/2)_PHP教程

class trie

{

private $trie;

function __construct()

{

$trie = array('children' => array(),'isword'=>false);

}

/**

* 把词加入词典

*

* @param string $key

*/

function &setword($word='')

{

$trienode = &$this->trie;

for($i = 0;$i < strlen($word);$i++)

{

$character = $word[$i];

if(!isset($trienode['children'][$character]))

{

$trienode['children'][$character] = array('isword'=>false);

}

if($i == strlen($word)-1)

{

$trienode['children'][$character] = array('isword'=>true);

}

$trienode = &$trienode['children'][$character];

}

}

/**

* 判断是否为词典词

*

* @param string $word

* @return bool true/false

*/

function & isword($word)

{

$trienode = &$this->trie;

for($i = 0;$i < strlen($word);$i++)

{

$character = $word[$i];

if(!isset($trienode['children'][$character]))

{

return false;

}

else

{

//判断词结束

if($i == (strlen($word)-1) && $trienode['children'][$character]['isword'] == true)

{

return true;

}

elseif($i == (strlen($word)-1) && $trienode['children'][$character]['isword'] == false)

{

return false;

}

$trienode = &$trienode['children'][$character];

}

}

}

/**

* 在文本$text找词出现的位置

*

* @param string $text

* @return array array('position'=>$position,'word' =>$word);

*/

function search($text="")

{

$textlen = strlen($text);

$trienode = $tree = $this->trie;

$find = array();

$wordrootposition = 0;//词根位置

$prenode = false;//回溯参数,当词典ab,在字符串aab中,需要把$i向前回溯一次

$word = '';

for ($i = 0; $i < $textlen;$i++)

{

if(isset($trienode['children'][$text[$i]]))

{

$word = $word .$text[$i];

$trienode = $trienode['children'][$text[$i]];

if($prenode == false)

{

$wordrootposition = $i;

}

$prenode = true;

if($trienode['isword'])

{

$find[] = array('position'=>$wordrootposition,'word' =>$word);

}

}

else

{

$trienode = $tree;

$word = '';

if($prenode)

{

$i = $i -1;

$prenode = false;

}

}

}

return $find;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值