在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