我想为字符串生成ngram字符。下面是我用过的Lucene 4.1 lib。
Reader reader = new StringReader(text);
NGramTokenizer gramTokenizer = new NGramTokenizer(reader, 3, 5); //catch contiguous sequence of 3, 4 and 5 characters
CharTermAttribute charTermAttribute = gramTokenizer.addAttribute(CharTermAttribute.class);
while (gramTokenizer.incrementToken()) {
String token = charTermAttribute.toString();
System.out.println(token);}
但是,我想使用Lucene 5.0.0来实现它。 NGramTokenizer在Lucene 5.0.0中从之前的版本中发生了很大的变化,请参考http://lucene.apache.org/core/5_0_0/analyzers-common/index.html?org/apache/lucene/analysis/ngram/NGramTokenizer.html。
任何人都知道如何使用Lucene 5.0.0来制作ngrams?
答案 0 :(得分:3)
以下代码:
StringReader stringReader = new StringReader("abcd");
NGramTokenizer tokenizer = new NGramTokenizer(1, 2);
tokenizer.setReader(stringReader);
tokenizer.reset();
CharTermAttribute termAtt = tokenizer.getAttribute(CharTermAttribute.class);
while (tokenizer.incrementToken()) {
String token = termAtt.toString();
System.out.println(token);
}
将产生:
a
ab
b
bc
c
cd
d