lucene学习--分词和高亮显示

首先在E:\TestLucene\workspaceSE路径下,建立文件夹indexdocs和3个txt文件:L1.txt,L2.txt,L3.txt.

L1.txt内容:

111111111111111111111111111111111111111111111111111111111111111111111111111
信息检索就是从信息集合中找出与用户需求相关的信息。
被检索的信息除了文本外,还有图像、音频、视频等多媒体信息,这里我们主要来说说文本信息的检索。
全文检索:把用户的查询请求和全文中的每一词进行比较,不考虑查询请求与文本语义上的匹配,
在信息检索工具中,全文检索是最具通用性和实用性的。(通俗的讲就是匹配关键字的)

数据检索:查询要求和信息系统中的数据都遵循一定的格式,具有一定的结构,
允许对特定的字段检索,其性能与使用有很大的局限性,并且支持语义匹配。

知识检索:强调的是基于知识的、语义的匹配(最复杂的,它就相当于我们知道了搜索问题的答案,
再直接去搜答案的信息)。

全文检索是指计算机索引程序通过扫描文章中的每一个词,对每一个词建立一个索引,
指明该词在文章中出现的次数和位置,当用户查询的时候,检索程序就根据事先建立好的索引进行查找,并将查找的结果反馈给用户的检索方式。

数据检索查询要求和信息系统中的数据都遵循一定的格式,具有一定的结构,允许对特定的字段检索。
例如,数据均按“时间、人物、地点、事件”的形式存储,查询可以为:地点=“北京”。数据检索的性能取决于所使用的标识字段的方法和用户对这种方法的理解,因此具有很大的局限性。

 

L2.txt内容:

 

2222222222222222222222222222222222222222222222222222222222222222222222222
说明:在Internet上采集信息的软件被称为爬虫或蜘蛛或网络机器人(搜索引擎外围的东西),
爬虫在Internet上访问每一个网页,每访问一个网页就把其中的内容传回本地服务器。
信息加工的最主要的任务就是为采集到本地的信息编排索引,为查询做好准备。
分词器的作用:分词器,对文本资源进行切分,将文本按规则切分成一个个进行索引的最小单位(关键词)

 


L3.txt内容:


333333333333333333333333333333333333333333333333333333333333333333333333
中文分词:中文的分词比较复杂,因为不是一个字就是一个词,
而且一个词在另外一个地方可能不是一个词,如在“帽子和服装”中,
“和服”就不是一个词,对于中文分词,通常有三种方式:单字分词、二分法分词、词典分词
单字分词:就是按照中文一个字一个字的分词
二分法分词:按两个字进行切分
词典分词:按某种算法构造词,然后去匹配已建好的词库集合,如果匹配到就切分出来成为词语,

 

准备工作完成了,现在看代码:

 

File2Document.java

 

[html]  view plain copy
  1. package lucene.study;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.IOException;  
  8. import java.io.InputStreamReader;  
  9. import java.io.UnsupportedEncodingException;  
  10.   
  11. import org.apache.lucene.document.Document;  
  12. import org.apache.lucene.document.Field;  
  13. import org.apache.lucene.document.Field.Index;  
  14. import org.apache.lucene.document.Field.Store;  
  15.   
  16. /**  
  17.  * @author xudongwang 2012-2-2  
  18.  *   
  19.  *         Email:xdwangiflytek@gmail.com  
  20.  */  
  21. public class File2Document {  
  22.     /**  
  23.      * File--->Document  
  24.      *   
  25.      * @param filePath  
  26.      *            File路径  
  27.      *   
  28.      * @return Document对象  
  29.      */  
  30.     public static Document file2Document(String filePath) {  
  31.         // 文件要存放:name,content,size,path  
  32.         File file = new File(filePath);  
  33.         Document document = new Document();  
  34.         // Store.YES 是否存储 yes no compress(压缩之后再存)  
  35.         // Index 是否进行索引 Index.ANALYZED 分词后进行索引,NOT_ANALYZED 不索引,NOT_ANALYZED  
  36.         // 不分词直接索引  
  37.         document.add(new Field("name", file.getName(), Field.Store.YES,  
  38.                 Field.Index.ANALYZED));  
  39.         document.add(new Field("content", readFileContent(file), Field.Store.YES,  
  40.                 Field.Index.ANALYZED));  
  41.         document.add(new Field("size", String.valueOf(file.length()),  
  42.                 Field.Store.YES, Field.Index.NOT_ANALYZED));// 不分词,但是有时需要索引,文件大小(int)转换成String  
  43.         document.add(new Field("path", file.getAbsolutePath(), Field.Store.YES,  
  44.                 Field.Index.NOT_ANALYZED));// 不需要根据文件的路径来查询  
  45.         return document;  
  46.     }  
  47.   
  48.     /**  
  49.      * 49. * 读取文件内容 50. * 51. * @param file 52. * File对象 53. * @return File的内容  
  50.      * 54.  
  51.      */  
  52.     private static String readFileContent(File file) {  
  53.         try {  
  54.             BufferedReader reader = new BufferedReader(new InputStreamReader(  
  55.                     new FileInputStream(file)));  
  56.             StringBuffer content = new StringBuffer();  
  57.             try {  
  58.                 for (String line = null; (line = reader.readLine()) != null;) {  
  59.                     content.append(line).append("\n");  
  60.                 }  
  61.             } catch (IOException e) {  
  62.   
  63.                 e.printStackTrace();  
  64.             }  
  65. //          try {  
  66. //              byte temp[]=content.toString().getBytes("UTF-8");  
  67. //              String tt=new String(temp,"gb2312");  
  68. //              System.out.println(tt);  
  69. //          } catch (UnsupportedEncodingException e) {  
  70. //              e.printStackTrace();  
  71. //          }  
  72.               
  73.               
  74.             return content.toString();  
  75.         } catch (FileNotFoundException e) {  
  76.   
  77.             e.printStackTrace();  
  78.         }  
  79.         return null;  
  80.     }  
  81.   
  82.     /**  
  83.      * <pre>  
  84.      * 获取name属性值的两种方法      
  85.      * 1.Filed field = document.getFiled("name");      
  86.      *         field.stringValue();      
  87.      * 2.document.get("name");  
  88.      * </pre>  
  89.      *   
  90.      * @param document  
  91.      */  
  92.     public static void printDocumentInfo(Document document) {  
  93.         // TODO Auto-generated method stub  
  94.         System.out.println("索引name -->" + document.get("name"));  
  95.         //System.out.println("content -->" + document.get("content"));  
  96.         System.out.println("索引path -->" + document.get("path"));  
  97.         System.out.println("索引size -->" + document.get("size"));  
  98.     }  
  99. }  


AnalyzerDemo.java

 

[html]  view plain copy
  1. package lucene.study;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.StringReader;  
  5.   
  6. import org.apache.lucene.analysis.Analyzer;  
  7. import org.apache.lucene.analysis.SimpleAnalyzer;  
  8. import org.apache.lucene.analysis.TokenStream;  
  9. import org.apache.lucene.analysis.cjk.CJKAnalyzer;  
  10. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  11. import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;  
  12. import org.apache.lucene.analysis.tokenattributes.TypeAttribute;  
  13. import org.apache.lucene.util.Version;  
  14.   
  15. public class AnalyzerDemo {  
  16.   
  17.     public void analyze(Analyzer analyzer, String text) {  
  18.   
  19.         System.out.println("-----------分词器:" + analyzer.getClass());  
  20.         TokenStream tokenStream = analyzer.tokenStream("content",  
  21.                 new StringReader(text));  
  22.   
  23.         CharTermAttribute termAtt = (CharTermAttribute) tokenStream  
  24.                 .getAttribute(CharTermAttribute.class);  
  25.           
  26. //      TypeAttribute typeAtt = (TypeAttribute) tokenStream.getAttribute(TypeAttribute.class);  
  27.   
  28.         try {  
  29.             while (tokenStream.incrementToken()) {  
  30.                 System.out.println(termAtt.toString());  
  31. //              System.out.println(typeAtt.type());  
  32.             }  
  33.         } catch (IOException e) {  
  34.             e.printStackTrace();  
  35.         }  
  36.   
  37.     }  
  38.       
  39.     public static void main(String[] dd){  
  40.         AnalyzerDemo  demo=new AnalyzerDemo();  
  41.         System.out.println("---------------测试英文");  
  42.         String enText = "Hello, my name is suolong, my 优快云 blog address is http://blog.youkuaiyun.com/lushuaiyin";     
  43.         System.out.println(enText);     
  44.           
  45.           
  46.         System.out.println("By StandardAnalyzer 方式分词:");     
  47.         Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);     
  48.         demo.analyze(analyzer, enText);  
  49.           
  50.         System.out.println("By SimpleAnalyzer 方式分词:");     
  51.         Analyzer analyzer2 = new SimpleAnalyzer(Version.LUCENE_35);     
  52.         demo.analyze(analyzer2, enText);  
  53.           
  54.         System.out.println("通过上面的结果发现StandardAnalyzer分词器不会按.来区分的,而SimpleAnalyzer是按.来区分的");     
  55.         System.out.println();  
  56.           
  57.           
  58.           
  59.         System.out.println("---------------->测试中文");     
  60.         String znText = "感谢原作王旭东";     
  61.         System.out.println(znText);     
  62.         System.out.println("By StandardAnalyzer 方式分词:");     
  63.         // 通过结果发现它是将每个字都作为一个关键字,这样的话效率肯定很低咯     
  64.         demo.analyze(analyzer, znText);     
  65.         System.out.println("By CJKAnalyzer 方式(二分法分词)分词:");     
  66.         Analyzer analyzer3 = new CJKAnalyzer(Version.LUCENE_35);     
  67.         demo.analyze(analyzer3, znText);  
  68.           
  69.           
  70.     }  
  71.   
  72. }  


控制台打印:

 

[html]  view plain copy
  1. ---------------测试英文  
  2. Hello, my name is suolong, my 优快云 blog address is http://blog.youkuaiyun.com/lushuaiyin  
  3. By StandardAnalyzer 方式分词:  
  4. -----------分词器:class org.apache.lucene.analysis.standard.StandardAnalyzer  
  5. hello  
  6. my  
  7. name  
  8. suolong  
  9. my  
  10. csdn  
  11. blog  
  12. address  
  13. http  
  14. blog.youkuaiyun.com  
  15. lushuaiyin  
  16. By SimpleAnalyzer 方式分词:  
  17. -----------分词器:class org.apache.lucene.analysis.SimpleAnalyzer  
  18. hello  
  19. my  
  20. name  
  21. is  
  22. suolong  
  23. my  
  24. csdn  
  25. blog  
  26. address  
  27. is  
  28. http  
  29. blog  
  30. csdn  
  31. net  
  32. lushuaiyin  
  33. 通过上面的结果发现StandardAnalyzer分词器不会按.来区分的,而SimpleAnalyzer是按.来区分的  
  34.   
  35. ---------------->测试中文  
  36. 感谢原作王旭东  
  37. By StandardAnalyzer 方式分词:  
  38. -----------分词器:class org.apache.lucene.analysis.standard.StandardAnalyzer  
  39. 感  
  40. 谢  
  41. 原  
  42. 作  
  43. 王  
  44. 旭  
  45. 东  
  46. By CJKAnalyzer 方式(二分法分词)分词:  
  47. -----------分词器:class org.apache.lucene.analysis.cjk.CJKAnalyzer  
  48. 感谢  
  49. 谢原  
  50. 原作  
  51. 作王  
  52. 王旭  
  53. 旭东  


 

高亮显示例子

HighLighterDemo.java

 

[html]  view plain copy
  1. package lucene.study;  
  2.   
  3. import java.io.File;  
  4.   
  5. import org.apache.lucene.analysis.Analyzer;  
  6. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  7. import org.apache.lucene.document.Document;  
  8. import org.apache.lucene.index.IndexReader;  
  9. import org.apache.lucene.index.IndexWriter;  
  10. import org.apache.lucene.index.IndexWriterConfig;  
  11. import org.apache.lucene.index.IndexWriterConfig.OpenMode;  
  12. import org.apache.lucene.queryParser.MultiFieldQueryParser;  
  13. import org.apache.lucene.queryParser.QueryParser;  
  14. import org.apache.lucene.search.Filter;  
  15. import org.apache.lucene.search.IndexSearcher;  
  16. import org.apache.lucene.search.Query;  
  17. import org.apache.lucene.search.ScoreDoc;  
  18. import org.apache.lucene.search.TopDocs;  
  19. import org.apache.lucene.search.highlight.Formatter;  
  20. import org.apache.lucene.search.highlight.Fragmenter;  
  21. import org.apache.lucene.search.highlight.Highlighter;  
  22. import org.apache.lucene.search.highlight.QueryScorer;  
  23. import org.apache.lucene.search.highlight.Scorer;  
  24. import org.apache.lucene.search.highlight.SimpleFragmenter;  
  25. import org.apache.lucene.search.highlight.SimpleHTMLFormatter;  
  26. import org.apache.lucene.store.Directory;  
  27. import org.apache.lucene.store.FSDirectory;  
  28. import org.apache.lucene.util.Version;  
  29.   
  30. public class HighLighterDemo {  
  31.   
  32.     /**  
  33.      * 源文件路径  
  34.      */  
  35.     private String filePath01 = "E:\\TestLucene\\workspaceSE\\L1.txt";  
  36.     private String filePath02 = "E:\\TestLucene\\workspaceSE\\L2.txt";  
  37.     private String filePath03 = "E:\\TestLucene\\workspaceSE\\L3.txt";  
  38.   
  39.     /**  
  40.      * 索引路径  
  41.      */  
  42.     private String indexPath = "E:\\TestLucene\\workspaceSE\\indexdocs";  
  43.   
  44.     /**  
  45.      * 分词器,这里我们使用默认的分词器,标准分析器(好几个,但对中文的支持都不好)  
  46.      */  
  47.     private Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);  
  48.   
  49.     /**  
  50.      * 创建索引  
  51.      *   
  52.      * @throws Exception  
  53.      */  
  54.     public void createIndex() throws Exception {  
  55.   
  56.         File indexFile = new File(indexPath);  
  57.         Directory directory = FSDirectory.open(indexFile);  
  58.   
  59.         // 写入器配置需要2个参数,版本,分词器。还有其他参数,这里就不再讲了。  
  60.         IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_35,  
  61.                 analyzer);  
  62.         conf.setOpenMode(OpenMode.CREATE);  
  63.   
  64.         // IndexWriter索引写入器是用来操作(增、删、改)索引库的  
  65.         IndexWriter indexWriter = new IndexWriter(directory, conf);// 需要两个参数,目录,写入器配置  
  66.   
  67.         // 文档,即要进行索引的单元  
  68.         Document doc01 = File2Document.file2Document(filePath01);  
  69.         Document doc02 = File2Document.file2Document(filePath02);  
  70.         Document doc03 = File2Document.file2Document(filePath03);  
  71.   
  72.         // 将Document添加到索引库中  
  73.         indexWriter.addDocument(doc01);  
  74.         indexWriter.addDocument(doc02);  
  75.         indexWriter.addDocument(doc03);  
  76.   
  77.         indexWriter.close();// 关闭写入器,释放资源,索引创建完毕  
  78.     }  
  79.   
  80.     /**  
  81.      * 搜索  
  82.      *   
  83.      * @param queryStr  
  84.      *            搜索的关键词  
  85.      * @throws Exception  
  86.      */  
  87.     public void search(String queryStr) throws Exception {  
  88.   
  89.         // 1、把要搜索的文本解析为Query对象  
  90.         // 指定在哪些字段查询  
  91.         String[] fields = { "name", "content" };  
  92.         // QueryParser: 是一个解析用户输入的工具,可以通过扫描用户输入的字符串,生成Query对象。  
  93.         QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_35,  
  94.                 fields, analyzer);  
  95.         // Query:查询,lucene中支持模糊查询,语义查询,短语查询,组合查询等等,如有TermQuery,BooleanQuery,RangeQuery,WildcardQuery等一些类。  
  96.         Query query = queryParser.parse(queryStr);  
  97.   
  98.         // 2、进行查询  
  99.         File indexFile = new File(indexPath);  
  100.   
  101.         // IndexSearcher 是用来在索引库中进行查询的  
  102.         Directory directory = FSDirectory.open(indexFile);  
  103.         IndexReader indexReader = IndexReader.open(directory);  
  104.         IndexSearcher indexSearcher = new IndexSearcher(indexReader);  
  105.         // Filter 过滤器,我们可以将查出来的结果进行过滤,可以屏蔽掉一些不想给用户看到的内容  
  106.         Filter filter = null;  
  107.         // 10000表示一次性在数据库中查询多少个文档  
  108.         // topDocs 类似集合  
  109.         TopDocs topDocs = indexSearcher.search(query, filter, 10000);  
  110.         System.out.println("总共有【" + topDocs.totalHits + "】个文档含有匹配\"" + queryStr  
  111.                 + "\"的结果");  
  112.         // 注意这里的匹配结果是指文档的个数,而不是文档中包含搜索结果的个数  
  113.   
  114.           
  115.           
  116.           
  117.         // 准备高亮器  
  118.         Formatter formatter = new SimpleHTMLFormatter("<font color='red'>",  
  119.                 "</font>");  
  120.         Scorer scorer = new QueryScorer(query);  
  121.         Highlighter highlighter = new Highlighter(formatter, scorer);  
  122.   
  123.         Fragmenter fragmenter = new SimpleFragmenter(100);// 指定100个字符  
  124.         highlighter.setTextFragmenter(fragmenter);// 决定是否生成摘要,以及摘要有多长  
  125.   
  126.         // 3、打印结果  
  127.         for (ScoreDoc scoreDoc : topDocs.scoreDocs) {  
  128.             int docSn = scoreDoc.doc;// 文档内部编号  
  129.             Document document = indexSearcher.doc(docSn);// 根据文档编号取出相应的文档  
  130.   
  131.             // 进行高亮处理  
  132.             // 返回高亮后的结果,如果当前属性值中没有出现关键字,会返回null  
  133.             String highlighterStr = highlighter.getBestFragment(analyzer,  
  134.                     "content", document.get("content"));  
  135.   
  136.             if (highlighterStr == null) {  
  137.                 String content = document.get("content");  
  138.                 int endIndex = Math.min(20, content.length());  
  139.                 highlighterStr = content.substring(0, endIndex);// 最多前20个字符  
  140.             }  
  141.             System.out.println("-------处理后的高亮内容------start------------");  
  142.             System.out.println(highlighterStr);  
  143.             System.out.println("-------处理后的高亮内容------end------------");  
  144.             document.getField("content").setValue(highlighterStr);  
  145.   
  146.             //File2Document.printDocumentInfo(document);// 打印出文档信息  
  147.         }  
  148.     }  
  149.   
  150.     public static void main(String[] args) throws Exception {  
  151.   
  152.         HighLighterDemo highLighterDemo = new HighLighterDemo();  
  153.         highLighterDemo.createIndex();// 创建索引  
  154.         // lucene.createRamIndex();//创建内存索引  
  155.   
  156.         highLighterDemo.search("分词");// 搜索你想找的文字  
  157.         System.out.println("--------------------------------------------------------------------");  
  158.         highLighterDemo.search("检索");  
  159.         System.out.println("--------------------------------------------------------------------");  
  160.         highLighterDemo.search("索引");  
  161.         System.out.println("--------------------------------------------------------------------");  
  162.     }  
  163.   
  164. }  


控制台打印:

 

[html]  view plain copy
  1. 总共有【3】个文档含有匹配"分词"的结果  
  2. -------处理后的高亮内容------start------------  
  3. 333333333333333333333333333333333333333333333333333333333333333333333333  
  4. 中文<font color='red'></font><font color='red'></font>:中文的<font color='red'></font><font color='red'></font>比较复杂,因为不是一个字就是一个  
  5. -------处理后的高亮内容------end------------  
  6. -------处理后的高亮内容------start------------  
  7. 。  
  8. <font color='red'></font><font color='red'></font>器的作用:<font color='red'></font><font color='red'></font>器,对文本资源进行切<font color='red'></font>,将文本按规则切<font color='red'></font>成一个个进行索引的最小单位(关键<font color='red'></font>)  
  9.   
  10. -------处理后的高亮内容------end------------  
  11. -------处理后的高亮内容------start------------  
  12. 息。  
  13. 被检索的信息除了文本外,还有图像、音频、视频等多媒体信息,这里我们主要来说说文本信息的检索。  
  14. 全文检索:把用户的查询请求和全文中的每一<font color='red'></font>进行比较,不考虑查询请求与文本语义上的匹配,  
  15. 在信息检索工  
  16. -------处理后的高亮内容------end------------  
  17. --------------------------------------------------------------------  
  18. 总共有【2】个文档含有匹配"检索"的结果  
  19. -------处理后的高亮内容------start------------  
  20. 111111111111111111111111111111111111111111111111111111111111111111111111111  
  21. 信息<font color='red'></font><font color='red'></font>就是从信息集合中找出与用户需求相关的信  
  22. -------处理后的高亮内容------end------------  
  23. -------处理后的高亮内容------start------------  
  24. 或蜘蛛或网络机器人(搜<font color='red'></font>引擎外围的东西),  
  25. 爬虫在Internet上访问每一个网页,每访问一个网页就把其中的内容传回本地服务器。  
  26. 信息加工的最主要的任务就是为采集到本地的信息编排<font color='red'></font>引,为查询做好准备  
  27. -------处理后的高亮内容------end------------  
  28. --------------------------------------------------------------------  
  29. 总共有【2】个文档含有匹配"索引"的结果  
  30. -------处理后的高亮内容------start------------  
  31. 或蜘蛛或网络机器人(搜<font color='red'></font><font color='red'></font>擎外围的东西),  
  32. 爬虫在Internet上访问每一个网页,每访问一个网页就把其中的内容传回本地服务器。  
  33. 信息加工的最主要的任务就是为采集到本地的信息编排<font color='red'></font><font color='red'></font>,为查询做好准备  
  34. -------处理后的高亮内容------end------------  
  35. -------处理后的高亮内容------start------------  
  36. 语义匹配。  
  37.   
  38. 知识检<font color='red'></font>:强调的是基于知识的、语义的匹配(最复杂的,它就相当于我们知道了搜<font color='red'></font>问题的答案,  
  39. 再直接去搜答案的信息)。  
  40.   
  41. 全文检<font color='red'></font>是指计算机<font color='red'></font><font color='red'></font>程序通过扫描文章中的每一个词,对每一个词建立一  
  42. -------处理后的高亮内容------end------------  
  43. --------------------------------------------------------------------  


 我把控制台打印的内容放到一个HTML网页中,看看效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值