內容審核、標籤推薦、垃圾訊息偵測等場景常需對文本進行關鍵詞匹配並計算權重。本文介紹一個基於 Trie 字典樹實作的 Weight 類別,支援多規則、多策略的靈活評分。
class Weight {
protected $dict = [[]]; // Trie 節點陣列
protected $items = []; // 待分析文本集合
protected $matches = []; // 匹配結果快取
protected $show = []; // 最終評分結果
protected $lastRule = ''; // 最後使用的評分規則
// 導入待分析文本
public function newItems($items) { ... }
// 導入規則表並建立字典
public function newTable(array $table) { ... }
// 取得評分結果
public function getShow($rule = 'max') { ... }
// 核心:建立字典樹
private function genDict($word, $key) { ... }
// 核心:匹配文本
public function matchWord($line) { ... }
}
$items = [
'chinaisbig',
'whichisnot',
'totalyrightforme',
];
// 規則表:格式 "分類,關鍵詞|權重,關鍵詞|權重..."
$table = [
'china,is|small',
'china,big|me',
'china,is|big,which|not,me',
'totaly|right,for,me',
];
$weight = new Weight();
$weight->newItems($items);
$weight->newTable($table);
// 取得最大權重分類
$result = $weight->getShow('max');
print_r($result);
/*
Array
(
[0] => Array ( [0] => me ) // china,big|me 命中
[1] => Array ( [0] => not ) // which|not 命中
[2] => Array ( [0] => right ) // totaly|right 命中
)
*/
| 場景 | 規則設計 | 評分策略 |
|---|---|---|
| 敏感詞過濾 | 分類: 關鍵詞|嚴重度 | max (最高嚴重度) |
| 文章自動標籤 | 標籤: 關鍵詞|關聯度 | 加權平均 / Top-N |
| 垃圾郵件偵測 | 規則: 特徵詞|權重 | 總分閾值判斷 |
| 搜尋排序加權 | 欄位: 關鍵詞|Boost值 | BM25 + 自定義權重 |