背景 :
在使用搜索引擎和電商的搜索功能時,大家一定遇到過這樣的情景:我想搜索電影“十二生肖”,可不小心輸成“十二生效”了,不用擔心搜不到你想要的結果,因為建立在大數據上的搜索引擎會幫你自動糾錯,就這個例子Google和Baidu返回給我的分別是:
顯示以下查詢字詞的結果: 十二生肖 和 您要找的是不是: 十二生肖 ,他們都做到了自動糾錯,關于自動糾錯我之前也寫過一篇陋文,當時是自己實現的N-Gram模型,但是效果不是太好,主要是針對不同的語料庫算法的精確度是不一樣的,我想換個算法試試看,目前主流的計算串間的距離(相反的,你也可以理解為相似度)是Levenshtein,當要實現時,發現lucene已經做了這個事,那咱就站在巨人的肩膀上成長吧。
引用包:
lucene-core-3.1.0.jar + lucene-spellchecker-3.1.0.jar,你可以在這里得到
使用示例:
在類SpellCorrector的main方法中加入以下代碼
1 //創建目錄
2 File dict = new File("");
3 Directory directory = FSDirectory.open(dict);
4
5 //實例化拼寫檢查器
6 SpellChecker sp = new SpellChecker(directory);
7
8
9 //創建詞典
10 File dictionary = new File(SpellCorrecter.class.getResource("dictionary.txt").getFile());
11
12 //對詞典進行索引
13 sp.indexDictionary(new PlainTextDictionary(dictionary));
14
15
16 //有錯別字的搜索
17 String search = "非常勿擾";
18
19
20 //建議個數,這里我只想要最接近的那一個,你可以設置成別的數字,如3
21 int suggestionNumber = 1;
22
23
24 //獲取建議的關鍵字
25 String[] suggestions = sp.suggestSimilar(search, suggestionNumber);
26
27
28 //顯示結果
29 System.out.println("搜索:" + search);
30
31
32 for (String word : suggestions) {
33 System.out.println("你要找的是不是:" + word);
34 }
2 File dict = new File("");
3 Directory directory = FSDirectory.open(dict);
4
5 //實例化拼寫檢查器
6 SpellChecker sp = new SpellChecker(directory);
7
8
9 //創建詞典
10 File dictionary = new File(SpellCorrecter.class.getResource("dictionary.txt").getFile());
11
12 //對詞典進行索引
13 sp.indexDictionary(new PlainTextDictionary(dictionary));
14
15
16 //有錯別字的搜索
17 String search = "非常勿擾";
18
19
20 //建議個數,這里我只想要最接近的那一個,你可以設置成別的數字,如3
21 int suggestionNumber = 1;
22
23
24 //獲取建議的關鍵字
25 String[] suggestions = sp.suggestSimilar(search, suggestionNumber);
26
27
28 //顯示結果
29 System.out.println("搜索:" + search);
30
31
32 for (String word : suggestions) {
33 System.out.println("你要找的是不是:" + word);
34 }
注:這之前你需要有個語料庫,我這里是個存放正確視頻名稱的文件,格式如下:
紅顏血淚
冰上火一般的激情
在敵之手
馳風競艇王第二部
釣金龜
瀟湘路一號
戲里戲外第二季
草原狼爵士樂
拯救大兵瑞恩
冰上火一般的激情
在敵之手
馳風競艇王第二部
釣金龜
瀟湘路一號
戲里戲外第二季
草原狼爵士樂
拯救大兵瑞恩
好了,接下來就直接運行吧,例如我搜索“十二生效”,則提示說是不是要找“十二生肖”
參考文獻
- http://lucene.apache.org/java/docs/
- http://today.java.net/pub/a/today/2005/08/09/didyoumean.html
- http://archsofty.blogspot.com/2009/12/adicione-o-recurso-voce-quis-dizer-nas.html
- http://lucene.apache.org/java/3_0_0/api/contrib-spellchecker/index.html
- http://en.wikipedia.org/wiki/Edit_distance
- http://en.wikipedia.org/wiki/Levenshtein_distance
- http://en.wikipedia.org/wiki/Jaro-Winkler_distance
http://www.cnblogs.com/wuren/archive/2013/01/16/2862873.html