public class MyTokenFilter extends TokenFilter {
private SameWord sameWord;
private Stack<String> stack;
private State currState;
private CharTermAttribute cta = addAttribute(CharTermAttribute.class);
private PositionIncrementAttribute pia = addAttribute(PositionIncrementAttribute.class);
protected MyTokenFilter(TokenStream input, SameWord sameWord) {
super(input);
this.sameWord = sameWord;
stack = new Stack<>();
}
@Override
public final boolean incrementToken() throws IOException {
// TODO Auto-generated method stub
if (stack.size() > 0) {
// 说明有同义词
// 1、取出一个同义词
String str = stack.pop();
// 还原状态
// 设置位置为0
pia.setPositionIncrement(0);
return true;
}
if (!input.incrementToken())
return false;
if (getSameWord(cta.toString())) {
currState = captureState();
}
return true;
}
/**
* 是否有同义词
*
* @param name
* @return
*/
private boolean getSameWord(String name) {
if (sameWord == null)
if (sames != null) {
for (String string : sames) {
stack.push(string);
}
return true;
}
return false;
private SameWord sameWord;
private Stack<String> stack;
private State currState;
private CharTermAttribute cta = addAttribute(CharTermAttribute.class);
private PositionIncrementAttribute pia = addAttribute(PositionIncrementAttribute.class);
protected MyTokenFilter(TokenStream input, SameWord sameWord) {
super(input);
this.sameWord = sameWord;
stack = new Stack<>();
}
@Override
public final boolean incrementToken() throws IOException {
// TODO Auto-generated method stub
if (stack.size() > 0) {
// 说明有同义词
// 1、取出一个同义词
String str = stack.pop();
// 还原状态
restoreState(currState);
//清空原数据
cta.setEmpty();
//添加同义词
cta.append(str);// 设置位置为0
pia.setPositionIncrement(0);
return true;
}
if (!input.incrementToken())
return false;
if (getSameWord(cta.toString())) {
currState = captureState();
}
return true;
}
/**
* 是否有同义词
*
* @param name
* @return
*/
private boolean getSameWord(String name) {
if (sameWord == null)
return false;
//取得该词的同义词
String[] sames = sameWord.getSameWord(name);if (sames != null) {
for (String string : sames) {
stack.push(string);
}
return true;
}
return false;
}
运行结果: