php简单分词,php版简易中文分词实现 – mysql版本

在chinaunix看到“php版简易中文分词实现”,原来的版本使用的是gdbm文本数据库,在php5下面测试老是不通过。今天将字典数据导入mysql,小小改动就可以用了.我觉得,如果要获取更好的性能,可以考虑将所有的词写入一个数组,并且写入内存(如memcache),查询速度应该有很大提高,不过今天没有时间试验了。

在class db_dictionary{}下面几行加入:

class db_dict extends db_dictionary {

var $_table = 'dict';

/** 加载词典 (参数: 词典路径) */

function load($fname) {

include_once('DB.php');

$this->_dbh = DB::connect($fname);

if (DB::isError($this->_dbh))

{

echo "fail to open the dictionary: $fname

" . CRLF;

die;

}

$res = $this->_dbh->query("SET NAMES 'gbk'"); //mysql 4.1以上要这行,否则注释掉

}

/** 查词 */

function find($word)

{

if (!DB::isError($this->_dbh))

{

$this->query_times++;

// check the cache

if ($this->has_cache && isset($this->_cache[$word]))

return $this->_cache[$word];

// query from db

$val = (int)$this->_dbh->getOne("SELECT `value`

FROM {$this->_table} WHERE `key`=?", array($word) );

// save to cache

if ($this->has_cache)

$this->_cache[$word] = $val;

return $val;

} else {

echo "you should load the dictionary file first!

" . CRLF;

die;

}

}

}

然后修改:

/** 分词类: 逆向最大 (2级复查词频比较) */

class cword_segment {

.................................

/** 设定词典 (根据后缀名确定类型) */

function set_dict($fname)

{

$this->_dict = new db_dict($fname);

}

.................................

}

调用的时候:

$wp->set_dict('mysql://root@localhost/test');

在win下php5.1.1 +apache 2.0.53测试通过,其中的include_once(‘DB.php’);是调用的Pear::DB

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值