【问题标题】:My word count program is not working我的字数统计程序不工作
【发布时间】:2016-12-03 14:02:44
【问题描述】:

下面的代码用于计算列表 y 中的单词在通过 FileReader 或列表 x 的文档中出现的次数。最终,我希望 list y 也成为导入的文档,但是当我在文档上运行代码时,它要么给我一个错误的计数,要么根本没有计数。怎么回事?

文件也是记事本形式。我正在使用窗户

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test {
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception {
        don w = new don();

        List<Integer> ist = new ArrayList<Integer>();
        // List<String> x =Arrays.asList
        // ("is","dishonorable","dismal","miserable","horrible","discouraging","distress","anguish","mine","is");

        BufferedReader in = new BufferedReader(new FileReader("this one.txt"));
        String str;

        List<String> list = new ArrayList<String>();
        while ((str = in.readLine()) != null) {
            list.add(str);
            // System.out.println(list);
            List<String> y = Arrays.asList("Hello", "the", "string", "is", "mine");
            for (String aY : y) {
                int count = 0;
                for (String aX : list) {
                    if (aY.contains(aX)) {
                        count++;
                    }
                }
                ist.add(count);
                // no need to reset the count
            }
            int g = ist .stream()
                        .mapToInt(value -> value)
                        .sum();
            System.out.println(g);
        }
    }
}

【问题讨论】:

  • don 对象应该做什么。你实例化它购买,之后你什么也不做。我不明白你为什么将count 存储在ArrayList
  • don 是我在问这个问题时打算取出的程序的一部分,因为它不相关。我正在存储计数,因为我想稍后用这个数字做其他事情。
  • 您的代码非常混乱,但我认为问题在于您正在将文档中的一行文本与字符串列表进行比较。所以它永远不会匹配
  • 我会建议您简化代码,以便我们可以专注于您的问题。并且不要与其他部分混淆。

标签: java arraylist bufferedreader filereader word-count


【解决方案1】:

如果你想数数,你应该……数数。

这里,你只检查字符串是否包含子字符串。

你应该做的大致如下:

static int count(String line, String word) {
  int count = 0;
  for (int offset = line.indexOf(word); offset >= 0; offset = line.indexOf(word, offset + 1 + word.length())) {
    count++;
  }
  return count;
}

现在,当然,您可能必须考虑到您正在寻找子字符串而不是单词的事实。但是,如果您已经了解了这一点,您可能希望使用正则表达式来进一步帮助您。

【讨论】:

    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多