lucene分词器解析

来源:互联网 发布:画结构式的软件 编辑:程序博客网 时间:2024/06/08 16:46
import java.io.IOException;import java.io.StringReader;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.cjk.CJKAnalyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;import org.apache.lucene.util.Version;import org.wltea.analyzer.lucene.IKAnalyzer;/** *  * 测试分词器... * @author Administrator * */public class TestAnalyzer {    /**     *      * 1、分词器的作用     *     在创建索引时会用到分词器,在使用字符串搜索时也会用到分词器,这两个地方要使用同一个分词器,否则可能会搜索不出结果。      Analyzer(分词器)的作用是把一段文本中的词按规则取出所包含的所有词。对应的是Analyzer类,这是一个抽象类,切分词的具体规则是由子类实现的,所以对于不同的语言(规则),要用不同的分词器         * @throws IOException      *      *      */    public static void main(String[] args) throws IOException {        //单字分词        //      Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_44);        //二分法分词...//      Analyzer analyzer=new CJKAnalyzer(Version.LUCENE_44);        //Analyzer 是一个抽象类,我们能不能改造它,来定义自己的分词规则..        //有没有第三方已经实现好了。我们直接拿过来用,        //google download  第三方 的一些开发工具包...        //github  很多第三方的资料...        //第三方的中文的分词器,庖丁分词器, 中文分词,特点:扩展新的词,自定义停用词...        //2012FF_u1        Analyzer analyzer=new IKAnalyzer();        //自定义扩展词...        String text="lucene 是传智播客的一个全文检索的高大上的工具包";        testAnalzyer(analyzer, text);    }    public static void testAnalzyer(Analyzer analyzer,String text) throws IOException{        System.out.println("当前使用的分词器:" + analyzer.getClass().getSimpleName());        TokenStream tokenStream = analyzer.tokenStream("content", new StringReader(text));        tokenStream.addAttribute(CharTermAttribute.class);        tokenStream.reset();        while (tokenStream.incrementToken()) {           CharTermAttribute charTermAttribute = tokenStream.getAttribute(CharTermAttribute.class);              System.out.println(new String(charTermAttribute.toString()));       }    }}

庖丁分词器首先要有一个IKAnalyzer.cfg.xml配置

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">  <properties>      <comment>IK Analyzer 扩展配置</comment>    <!--用户可以在这里配置自己的扩展字典-->     <entry key="ext_dict">mydict.dic;</entry>      <!--用户可以在这里配置自己的扩展停止词字典-->    <entry key="ext_stopwords">ext_stopword.dic</entry> </properties>

建立一个扩展词典mydict.dic文件,内容如下所示

传智播客高大上

建立一个扩展停止词字典ext_stopword.dic,内容如下所示

也了仍从以使则却又及对就并很或把是的着给而被让在还比等当与于但乃一个包上
原创粉丝点击