Lucene4.3进阶开发之神游北冥(十八)
Lucene作为一款优秀的全文检索工具包,自然附带了一些其他比较有用的功能,例如在文本挖掘领域,常常需要统计一些词或短语的TF信息,或者IDF的信息,用来加权某个词条,从而找出某篇新闻,或文献中比较重要的一些关键词或短语,或者我们想得到这些词库的位置信息等等。
首先,第一个我们来看下如何获取分词后的短语的位置信息,这个功能,主要跟我们的分词器有关系,在分词过程中记录的位置信息,增量信息,载荷等等,我们重点来看下,如何获取位置信息,代码如下:
最后,我们来看下,如何获取IDF,
Lucene作为一款优秀的全文检索工具包,自然附带了一些其他比较有用的功能,例如在文本挖掘领域,常常需要统计一些词或短语的TF信息,或者IDF的信息,用来加权某个词条,从而找出某篇新闻,或文献中比较重要的一些关键词或短语,或者我们想得到这些词库的位置信息等等。
首先,第一个我们来看下如何获取分词后的短语的位置信息,这个功能,主要跟我们的分词器有关系,在分词过程中记录的位置信息,增量信息,载荷等等,我们重点来看下,如何获取位置信息,代码如下:
- public void postion(String word)throws Exception{
- Analyzer analyzer=new IKAnalyzer();//IK分词
- TokenStream token=analyzer.tokenStream("a", new StringReader(word));
- token.reset();
- CharTermAttribute term=token.addAttribute(CharTermAttribute.class);//term信息
- OffsetAttribute offset=token.addAttribute(OffsetAttribute.class);//位置数据
- while(token.incrementToken()){
- System.out.println(term+" "+offset.startOffset()+" "+offset.endOffset());
- }
- token.end();
- token.close();
- }
- FieldType ft=new FieldType();
- ft.setIndexed(true);//存储
- ft.setStored(true);//索引
- ft.setStoreTermVectors(true);
- ft.setTokenized(true);
- ft.setStoreTermVectorPositions(true);//存储位置
- ft.setStoreTermVectorOffsets(true);//存储偏移量
- Document doc=new Document();
- doc.add(new Field("name", word, ft));
- writer.addDocument(doc);
- Directory directroy=FSDirectory.open(new File("D:\\lucene测试索引\\2014311测试"));
- IndexReader reader= DirectoryReader.open(directroy);
- for (int i = 0; i < reader.numDocs(); i++) {
- int docId = i;
- System.out.println("第"+(i+1)+"篇文档:");
- Terms terms = reader.getTermVector(docId, "name");
- if (terms == null)
- continue;
- TermsEnum termsEnum = terms.iterator(null);
- BytesRef thisTerm = null;
- while ((thisTerm = termsEnum.next()) != null) {
- String termText = thisTerm.utf8ToString();
- DocsEnum docsEnum = termsEnum.docs(null, null);
- while ((docsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
- System.out.println("termText:"+termText+" TF: "+docsEnum.freq());
- }
- }
- }
最后,我们来看下,如何获取IDF,
- Directory directroy=FSDirectory.open(new File("D:\\lucene测试索引\\2014311测试"));
- IndexReader reader= DirectoryReader.open(directroy);
- List<AtomicReaderContext> list=reader.leaves();
- for(AtomicReaderContext ar:list){
- String field="name";
- AtomicReader areader=ar.reader();
- Terms term=areader.terms("name");
- TermsEnum tn=term.iterator(null);
- BytesRef text;
- while((text = tn.next()) != null) {
- System.out.println("field=" + field + "; text=" + text.utf8ToString()+" IDF : "+tn.docFreq()
- // +" 全局词频 : "+tn.totalTermFreq()
- );
- }
- }
No comments:
Post a Comment