【问题标题】:java weka stringtowordvector is not counting word occurences properlyjava weka stringtoword 向量没有正确计算单词的出现次数
【发布时间】:2011-10-11 09:00:53
【问题描述】:

所以我正在使用 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 应该计算字符串中出现的单词,而不是让单词“repeat”计数 3 次,但计数结果仅为 1

我做错了什么?

【问题讨论】:

    标签: java string api machine-learning weka


    【解决方案1】:

    默认设置仅将存在/不存在报告为 0/1。您必须明确启用计数。添加:

    filter.setOutputWordCounts(true);

    然后重新运行。

    Weka 有一个明确的邮件列表;在此处发布此类问题可能会给您更快的答复。

    【讨论】:

      【解决方案2】:

      哎呀...所有这些代码行。换成这几行怎么样?

      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}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-25
        • 2011-02-07
        • 1970-01-01
        • 2018-01-02
        • 2012-08-09
        • 2021-11-17
        相关资源
        最近更新 更多