java weka stringtowordvector is not counting word occurences properly

▼魔方 西西 提交于 2019-12-05 21:00:22

Gee... all those lines of code. How about these few lines instead?

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;
}

Here's the code in action:

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

Output:

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

The default setting is only reporting presence/absence as 0/1. You must enable counting explicitly. Add:

filter.setOutputWordCounts(true);

and re-run.

Weka has an explicit mailing list; posting such questions there might give you faster responses.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!