十五、实现简单同义词分词器

public interface SamewordContext {
    public String[] getSamewords(String name);
}



public class MySameTokenFilter extends TokenFilter {
    private CharTermAttribute            cta        = null;
    private PositionIncrementAttribute    pia        = null;
    private AttributeSource.State        current;
    private Stack<String>                sames    = null;
    private final SamewordContext        samewordContext;
   
    protected MySameTokenFilter(TokenStream input, SamewordContext samewordContext) {
        super(input);
        cta = this.addAttribute(CharTermAttribute.class);
        pia = this.addAttribute(PositionIncrementAttribute.class);
        sames = new Stack<String>();
        this.samewordContext = samewordContext;
    }
   

    //找到同义词,在相同的位置上叠加
    @Override
    public boolean incrementToken() throws IOException {
       
if (sames.size() > 0) {
            //将元素出栈,并且获取这个同义词
            String str = sames.pop();
            //还原状态
            restoreState(current);
            cta.setEmpty();
            cta.append(str);
            //设置位置0
            pia.setPositionIncrement(0);
            return true;
        }
       
        if (!this.input.incrementToken())
            return false;
       
        if (addSames(cta.toString())) {
            //如果有同义词将当前状态先保存
            current = captureState();
        }
        return true;

    }
   
    private boolean addSames(String name) {
        String[] sws = samewordContext.getSamewords(name);
        if (sws != null) {
            for (String str : sws) {
                sames.push(str);
            }
            return true;
        }
        return false;
    }
   
}


public class MySameAnalyzer extends Analyzer {
    private final SamewordContext    samewordContext;
   
    public MySameAnalyzer(SamewordContext swc) {
        samewordContext = swc;
    }
   
    @Override
    public TokenStream tokenStream(String fieldName, Reader reader) {
        //Dictionary dic = Dictionary.getInstance("D:\\tools\\javaTools\\lucene\\mmseg4j-1.8.5\\data");
        Dictionary dic = Dictionary.getInstance();
        return
new MySameTokenFilter(new MMSegTokenizer(new MaxWordSeg(dic), reader),
            samewordContext);

    }
   
}



你可能感兴趣的:(同义词)