如何在使用lucene分析器时添加短语作为停用词?

时间:2015-01-25 20:55:48

标签: java lucene tokenize

我正在使用Lucene 4.6.1库。我试图在我的禁用词排除列表中添加单词 - hip hop。

我可以将它排除在外 - 如果它写成 - hiphop(作为一个单词)但是当它写成嘻哈(中间有空格)时我不能排除它。

以下是我的排除列表逻辑 -

public static final CharArraySet STOP_SET_STEM = new CharArraySet(LUCENE_VERSION, Arrays.asList(

"hiphop","hip hop"

), false);

有关我的自定义分析器逻辑的更多详细信息 -

下面的

是我的惯用手术逻辑 -

public final class CustomWordsAnalyzer extends StopwordAnalyzerBase {
  private static final Version LUCENE_VERSION = Version.LUCENE_46;

  // Regex used to exclude non-alpha-numeric tokens
  private static final Pattern ALPHA_NUMERIC = Pattern.compile("^[a-z][a-z0-9_]+$");
  private static final Matcher MATCHER = ALPHA_NUMERIC.matcher("");

  public CustomWordsAnalyzer() {
    super(LUCENE_VERSION, ProTextWordLists.STOP_SET);
  }

  public CustomWordsAnalyzer(CharArraySet stopSet) {
    super(LUCENE_VERSION, stopSet);

  }

  @Override
  protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
    Tokenizer tokenizer = new StandardTokenizer(LUCENE_VERSION, reader);
    TokenStream result = new StandardFilter(LUCENE_VERSION, tokenizer);
    result = new LowerCaseFilter(LUCENE_VERSION, result);
    result = new ASCIIFoldingFilter(result);
    result = new AlphaNumericMaxLengthFilter(result);
    result = new StopFilter(LUCENE_VERSION, result, ProTextWordLists.STOP_SET);

    result = new PorterStemFilter(result);
    result = new StopFilter(LUCENE_VERSION, result, ProTextWordLists.STOP_SET_STEM);
    return new TokenStreamComponents(tokenizer, result);
  }

  /**
   * Matches alpha-numeric tokens between 2 and 40 chars long.
   */
  static class AlphaNumericMaxLengthFilter extends TokenFilter {
    private final CharTermAttribute termAtt;
    private final char[] output = new char[28];

    AlphaNumericMaxLengthFilter(TokenStream in) {
      super(in);
      termAtt = addAttribute(CharTermAttribute.class);
    }

    @Override
    public final boolean incrementToken() throws IOException {
      // return the first alpha-numeric token between 2 and 40 length
      while (input.incrementToken()) {
        int length = termAtt.length();
        if (length >= 3 && length <= 28) {
          char[] buf = termAtt.buffer();
          int at = 0;
          for (int c = 0; c < length; c++) {
            char ch = buf[c];
            if (ch != '\'') {
              output[at++] = ch;
            }
          }
          String term = new String(output, 0, at);
          MATCHER.reset(term);
          if (MATCHER.matches() && !term.startsWith("a0")) {
            termAtt.setEmpty();
            termAtt.append(term);
            return true;
          }
        }
      }
      return false;
    }
  }
}

1 个答案:

答案 0 :(得分:0)

使用默认的Lucene实现无法完成,唯一的方法就是创建自己的Analyzer或TokenStream,它们将以您需要的方式处理数据/查询(例如过滤短语)< / p>