有沒有一種簡單的方法可以使用Lucene的Analyzer
的任何子類來解析/標記String
?如何使用Lucene分析器來標記字符串?
喜歡的東西:
String to_be_parsed = "car window seven";
Analyzer analyzer = new StandardAnalyzer(...);
List<String> tokenized_string = analyzer.analyze(to_be_parsed);
有沒有一種簡單的方法可以使用Lucene的Analyzer
的任何子類來解析/標記String
?如何使用Lucene分析器來標記字符串?
喜歡的東西:
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;
}
}
請詳細說明AFAIK的含義。謝謝。 – Neal 2011-06-13 19:18:42
這正是我所期待的。謝謝。 – 2011-06-13 19:26:28
只需再注意一點:從Lucene 3.2開始,不推薦使用TermAttribute來支持CharTermAttribute。 – 2011-06-13 19:30:34
根據上面的答案,它稍作修改以適用於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;
}
}
在Lucene 4.1中,您還需要在'while'語句之前添加'stream.reset()' – prestomanifesto 2013-02-28 19:29:33
@prestomanifesto:保存我的日子:-) – Salil 2013-05-13 12:11:58
您可能需要添加'stream.end(); stream.close();'在斜坡之後。 – membersound 2014-09-04 07:42:01
這是你問的一個非常模糊的問題。答案是「是」。但是,這取決於你想如何解析/標記所述字符串。 – stevevls 2011-06-13 18:39:34
@stevevls增加了一個例子。我使用列表,但它不一定必須是列表。 –
2011-06-13 18:44:59