编程语言
首页 > 编程语言> > java weka stringtowordvector没有正确计算单词出现次数

java weka stringtowordvector没有正确计算单词出现次数

作者:互联网

所以我正在使用Weka机器学习库的JAVA API,我有以下代码:

    String html = "repeat repeat repeat";

    Attribute input = new Attribute("html",(FastVector) null);

    FastVector inputVec = new FastVector();
    inputVec.addElement(input);

    Instances htmlInst = new Instances("html",inputVec,1);
    htmlInst.add(new Instance(1));  
    htmlInst.instance(0).setValue(0, html);

    StringToWordVector filter = new StringToWordVector();
    filter.setUseStoplist(true);

    filter.setInputFormat(htmlInst);
    Instances dataFiltered = Filter.useFilter(htmlInst, filter);

    Instance last = dataFiltered.lastInstance();
    System.out.println(last);

虽然StringToWordVector应该计算字符串中出现的单词,而不是将“重复”一词计数3次,但计数仅为1

我究竟做错了什么?

解决方法:

哎呀……所有这些代码行.相反,这几行怎么样?

public static Map<String, Integer> countWords(String input) {
    Map<String, Integer> map = new HashMap<String, Integer>();
    Matcher matcher = Pattern.compile("\\b\\w+\\b").matcher(input);
    while (matcher.find())
        map.put(matcher.group(), map.containsKey(matcher.group()) ? map.get(matcher.group()) + 1 : 1);
    return map;
}

这是代码的实际应用:

public static void main(String[] args) {
    System.out.println(countWords("sample, repeat sample, of text"));
}

输出:

{of=1, text=1, repeat=1, sample=2}

标签:java,string,machine-learning,api,weka
来源: https://codeday.me/bug/20190826/1734539.html