[ lucene擴充套件 ] spellChecker原理分析
阿新 • • 發佈:2019-01-11
spellChecker是用來對使用者輸入的“檢索內容”進行校正,例如百度上搜索“麻辣將”,他的提示如下圖所示:
我們首先借用lucene簡單實現該功能。
本文內容如下(簡單實現、原理簡介、現有問題)
lucene中spellchecker簡述
lucene 的擴充套件包中包含了spellchecker,利用它我們可以方便的實現拼寫檢查的功能,但是檢查的效果(推薦的準確程度)需要開發者進行調整、優化。
lucene實現“拼寫檢查”的步驟
步驟1:建立spellchecker所需的索引檔案
spellchecker也需要藉助lucene的索引實現的,只不過其採用了特殊的分詞方式和相關度計算方式。
建立spellchecker所需的索引檔案可以用文字檔案提供內容,一行一個片語,類似於字典結構。
例如(dic.txt):
麻辣燙
中文測試
麻辣醬
麻辣火鍋
中國人
中華人民共和國
|
建立spellchecker索引的關鍵程式碼如下:
/**
*
根據字典檔案建立spellchecker所使用的索引。
*
*
@param spellIndexPath
*
spellchecker索引檔案路徑 *
@param idcFilePath
*
原始字典檔案路徑
*
@throws IOException
*/
public void createSpellIndex(String
spellIndexPath, String idcFilePath)
throws IOException
{
Directory
spellIndexDir = FSDirectory.open( new File(spellIndexPath));
SpellChecker
spellChecker = new SpellChecker(spellIndexDir);
IndexWriterConfig
config = new IndexWriterConfig(Version.LUCENE_35,
null );
spellChecker.indexDictionary( new PlainTextDictionary( new File(
idcFilePath)),
config, false );
//
close
spellIndexDir.close();
spellChecker.close();
}
|
這裡使用了PlainTextDictionary物件,他實現了Dictionary介面,類結構如下圖所示:
除了PlainTextDictionary(1 word per line),我們還可以使用:
- FileDictionary(1 string per line, optionally with a tab-separated integer value | 片語之間用tab分隔)
- LuceneDictionary(Lucene Dictionary: terms taken from the given field of a Lucene index | 用現有的index的term建立索引)
- HighFrequencyDictionary(HighFrequencyDictionary: terms taken from the given field of a Lucene index, which appear in a number of documents above a given threshold. | 在LuceneDictionary的基礎上加入了一定的限定,term只有出現在各document中的次數滿足一定數量時才被spellchecker採用)
例如我們採用luceneDictionary,主要程式碼如下:
/**
*
根據指定索引中的字典建立spellchecker所使用的索引。
*
*
@param oriIndexPath
*
指定原始索引
*
@param fieldName
*
索引欄位(某個欄位的字典)
*
@param spellIndexPath
*
原始字典檔案路徑
*
@throws IOException
*/
public void createSpellIndex(String
oriIndexPath, String fieldName,
|