如何在 WEKA (Java) 中使用自定义停用词和词干分析器文件?

How do I use custom stopwords and stemmer file in WEKA (Java)?

到目前为止我有:

NGramTokenizer tokenizer = new NGramTokenizer();
tokenizer.setNGramMinSize(2);
tokenizer.setNGramMaxSize(2); 
tokenizer.setDelimiters("[\w+\d+]");

StringToWordVector filter = new StringToWordVector();
// customize filter here
Instances data = Filter.useFilter(input, filter);

API对StringToWordVector有这两个方法:

setStemmer(Stemmer value);
setStopwordsHandler(StopwordsHandler value);

我有一个包含停用词的文本文件和另一个 class 词干。如何使用自定义词干分析器和停用词过滤器?请注意,我正在使用大小为 2 的短语,因此我无法预先预处理和删除所有停用词。

更新:这对我有用(使用 Weka 开发人员版本 3.7.12)

要使用自定义停用词处理程序:

public class MyStopwordsHandler implements StopwordsHandler {

    private HashSet<String> myStopwords;

    public MyStopwordsHandler() {
        //Load in your own stopwords, etc.
    }

    //Must implement this method from the StopwordsHandler interface
    public Boolean isStopword(String word) {
        return myStopwords.contains(word); 
    }

}

要使用自定义词干分析器,请创建一个实现词干分析器接口的 class 并编写这些方法的实现:

public String stem(String word) { ... }
public String getRevision() { ... } 

然后使用您的自定义停用词处理程序和词干分析器:

StringToWordVector filter = new StringToWordVector();
filter.setStemmer(new MyStemmer());
filter.setStopwordsHandler(new MyStopwordsHandler());

注意: Thusitha 下面的答案适用于稳定的 3.6 版本,它比上面描述的要简单得多。但是我无法让它与 3.7.12 版本一起使用。

在最新的 weka 库中你可以使用

StringToWordVector filter = new StringToWordVector();
filter.setStopwords(new File("filename"));

我正在使用以下依赖项

<dependency>
   <groupId>nz.ac.waikato.cms.weka</groupId>
   <artifactId>weka-stable</artifactId>
   <version>3.6.12</version>
</dependency>

在 API 文档中 API Doc

public void setStopwords(java.io.File value) sets the file containing the stopwords, null or a directory unset the stopwords. If the file exists, it automatically turns on the flag to use the stoplist. Parameters: value - the file containing the stopwords