搜索引擎與電商平台常見的「您是不是要找」功能,如輸入「博客員」自動糾正為「博客園」。傳統 N-Gram 模型效果受限於語料庫,採用 Lucene 成熟的拼寫檢查器基於編輯距離 (Levenshtein) 實現更通用的糾錯。
lucene-core-3.1.0.jarlucene-spellchecker-3.1.0.jarpublic class SpellCorrector {
public static void main(String[] args) throws Exception {
// 1. 創建索引目錄
File dictDir = new File("spell_index");
Directory directory = FSDirectory.open(dictDir);
// 2. 實例化拼寫檢查器
SpellChecker spellChecker = new SpellChecker(directory);
// 3. 構建詞典 (PlainTextDictionary 讀取每行一詞)
File dictionary = new File(SpellCorrector.class.getResource("dictionary.txt").getFile());
spellChecker.indexDictionary(new PlainTextDictionary(dictionary));
// 4. 糾錯查詢
String query = "非常勿擾"; // 錯誤輸入
String[] suggestions = spellChecker.suggestSimilar(query, 1); // 取最相似 1 條
System.out.println("建議: " + Arrays.toString(suggestions));
// 輸出: 建議: [非誠勿擾]
}
}
紅顏血淚
冰上火一般的激情
在敵之手
馳風競艇王第二部
釣金龜
潇湘路一號
戲裡戲外第二季
草原狼爵士樂
拯救大兵瑞恩
非誠勿擾
...

輸入「非常勿擾」精準糾正為「非誠勿擾」。
SpellChecker.addDictionary() 增量更新RAMDirectory) 加速Lucene SpellChecker 提供開箱即用的拼寫糾錯能力,基於編輯距離演算法,適合中英文混合、實體名稱糾錯場景。接入成本低,效果優於自研 N-Gram 模型,是構建「您是不是要找」功能的首選方案。