如何使用Lucene Analyzer标记字符串?

| 有没有一种简单的方法可以使用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-with-resources会更好!这样,您就不必显式调用库的更高版本中必需的ѭ5。
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;
}
和Tokenizer版本:
  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...
  }
    

要回复问题请先登录注册