SCWS(Simple Chinese Word Segmentation)是一套基於詞頻詞典的機械式中文分詞引擎,由 hightman 開發,採 BSD 授權開源。核心以純 C 語言撰寫,無外部依賴,支援 GBK、UTF-8 等編碼,並提供 PHP 擴展模組,可直接在 PHP 程式中高效呼叫。分詞準確率約 90%~95%,適合小型搜尋引擎、關鍵字提取、文字分析等場景。
wget -c https://www.xunsearch.com/scws/down/scws-1.2.1.tar.bz2
tar jxvf scws-1.2.1.tar.bz2
cd scws-1.2.1
./configure --prefix=/usr/local/scws
make && make install
cd phpext
phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install
隨後編輯 php.ini 載入擴展:
extension = scws.so
scws.default.charset = utf-8
scws.default.fpath = /usr/local/scws/etc/
wget https://www.xunsearch.com/scws/down/scws-dict-chs-utf8.tar.bz2
tar jxvf scws-dict-chs-utf8.tar.bz2 -C /usr/local/scws/etc/
chown www:www /usr/local/scws/etc/dict.utf8.xdb
<?php
$so = scws_new();
$so->set_charset('utf-8');
$so->set_dict('/usr/local/scws/etc/dict.utf8.xdb');
$so->set_rule('/usr/local/scws/etc/rules.utf8.ini');
$so->set_ignore(true); // 忽略標點
$so->set_multi(true); // 複式分割(如「中國人」→「中國、人、中國人」)
$so->set_duality(true); // 雙字聚合
$so->send_text('歡迎來到火星時代 IT 開發');
while ($res = $so->get_result()) {
print_r($res);
/* 回傳陣列結構:
word => 詞彙本身
idf => 逆文件頻率 (float)
off => 原文位置 (int)
attr => 詞性標註 (string)
*/
}
$so->close();
| 欄位 | 型別 | 說明 |
|---|---|---|
| word | string | 分出的詞彙 |
| idf | float | 逆文件頻率,可作關鍵字權重參考 |
| off | int | 詞彙在原文的位移 |
| attr | string | 詞性(如 n=名詞、v=動詞、ns=地名等) |
若不想自建環境,可直接呼叫官方 API:
https://www.xunsearch.com/scws/api.php
支援 GET/POST,回傳 JSON 格式,適合低頻率呼叫或快速原型開發。
php-dev 或 php-devel 套件scws.default.fpath 指向正確目錄且結尾有斜線iconv 轉換