我目前正在为 Mahout 集群项目开发自定义分析器。由于 Mahout 0.8 将 Lucene 更新到 4.3,我无法从本书过时的示例中生成标记化文档文件或 SequenceFile。以下代码是我对 Mahout in Action 书中示例代码的修改。但是,它给了我非法状态异常。
public class MyAnalyzer extends Analyzer {
private final Pattern alphabets = Pattern.compile("[a-z]+");
Version version = Version.LUCENE_43;
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer source = new StandardTokenizer(version, reader);
TokenStream filter = new StandardFilter(version, source);
filter = new LowerCaseFilter(version, filter);
filter = new StopFilter(version, filter, StandardAnalyzer.STOP_WORDS_SET);
CharTermAttribute termAtt = (CharTermAttribute)filter.addAttribute(CharTermAttribute.class);
StringBuilder buf = new StringBuilder();
try {
filter.reset();
while(filter.incrementToken()){
if(termAtt.length()>10){
continue;
}
String word = new String(termAtt.buffer(), 0, termAtt.length());
Matcher matcher = alphabets.matcher(word);
if(matcher.matches()){
buf.append(word).append(" ");
}
}
} catch (IOException e) {
e.printStackTrace();
}
source = new WhitespaceTokenizer(version, new StringReader(buf.toString()));
return new TokenStreamComponents(source, filter);
}
}