有一个简单的方法,我可以使用Lucene的Analyzer
的任何子类解析/记号化一个String
?
就像是:
String to_be_parsed = "car window seven";
Analyzer analyzer = new StandardAnalyzer(...);
List<String> tokenized_string = analyzer.analyze(to_be_parsed);
据我所知,你必须自己写循环。像这样的事情(从我的源代码树直取):
public final class LuceneUtils {
public static List<String> parseKeywords(Analyzer analyzer, String field, String keywords) {
List<String> result = new ArrayList<String>();
TokenStream stream = analyzer.tokenStream(field, new StringReader(keywords));
try {
while(stream.incrementToken()) {
result.add(stream.getAttribute(TermAttribute.class).term());
}
}
catch(IOException e) {
// not thrown b/c we're using a string reader...
}
return result;
}
}
基于以上关闭的答案,这是略作修改使用Lucene 4.0工作。
public final class LuceneUtil {
private LuceneUtil() {}
public static List<String> tokenizeString(Analyzer analyzer, String string) {
List<String> result = new ArrayList<String>();
try {
TokenStream stream = analyzer.tokenStream(null, new StringReader(string));
stream.reset();
while (stream.incrementToken()) {
result.add(stream.getAttribute(CharTermAttribute.class).toString());
}
} catch (IOException e) {
// not thrown b/c we're using a string reader...
throw new RuntimeException(e);
}
return result;
}
}
即使是使用try-与资源更好!这样,您就不必显式调用了在更高的版本库的需要.close()
。
public static List<String> tokenizeString(Analyzer analyzer, String string) {
List<String> tokens = new ArrayList<>();
try (TokenStream tokenStream = analyzer.tokenStream(null, new StringReader(string))) {
tokenStream.reset(); // required
while (tokenStream.incrementToken()) {
tokens.add(tokenStream.getAttribute(CharTermAttribute.class).toString());
}
} catch (IOException e) {
new RuntimeException(e); // Shouldn't happen...
}
return tokens;
}
和标记生成器的版本:
try (Tokenizer standardTokenizer = new HMMChineseTokenizer()) {
standardTokenizer.setReader(new StringReader("我说汉语说得很好"));
standardTokenizer.reset();
while(standardTokenizer.incrementToken()) {
standardTokenizer.getAttribute(CharTermAttribute.class).toString());
}
} catch (IOException e) {
new RuntimeException(e); // Shouldn't happen...
}