php简单分词,php版简易中文分词实现 – mysql版本
在chinaunix看到“php版簡(jiǎn)易中文分詞實(shí)現(xiàn)”,原來的版本使用的是gdbm文本數(shù)據(jù)庫,在php5下面測(cè)試?yán)鲜遣煌ㄟ^。今天將字典數(shù)據(jù)導(dǎo)入mysql,小小改動(dòng)就可以用了.我覺得,如果要獲取更好的性能,可以考慮將所有的詞寫入一個(gè)數(shù)組,并且寫入內(nèi)存(如memcache),查詢速度應(yīng)該有很大提高,不過今天沒有時(shí)間試驗(yàn)了。
在class db_dictionary{}下面幾行加入:
class db_dict extends db_dictionary {
var $_table = 'dict';
/** 加載詞典 (參數(shù): 詞典路徑) */
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級(jí)復(fù)查詞頻比較) */
class cword_segment {
.................................
/** 設(shè)定詞典 (根據(jù)后綴名確定類型) */
function set_dict($fname)
{
$this->_dict = new db_dict($fname);
}
.................................
}
調(diào)用的時(shí)候:
$wp->set_dict('mysql://root@localhost/test');
在win下php5.1.1 +apache 2.0.53測(cè)試通過,其中的include_once(‘DB.php’);是調(diào)用的Pear::DB
總結(jié)
以上是生活随笔為你收集整理的php简单分词,php版简易中文分词实现 – mysql版本的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么java可跨平台执行,java为什
- 下一篇: groovy oracle数据库,使用G