【问题标题】:Why is my word counter sometimes off by one?为什么我的单词计数器有时会减一?
【发布时间】:2016-05-17 05:04:28
【问题描述】:

大部分时间它都能正常工作。很少会倒数。有什么猜测吗?

public static int countWords(File file) throws FileNotFoundException, IOException{
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        List<String> strList = new ArrayList<>();

        while ((line=br.readLine())!=null){
            String[] strArray= line.split("\\s+");
            for (int i=0; i<strArray.length;i++){
                strList.add(strArray[i]);
            }
        }
        return strList.size();

    }

特别是在下面的示例中,它给出的是 3 而不是 2:

\n
             k

【问题讨论】:

  • 您认为\n 是一个词吗?我认为k 是您示例中唯一的 word
  • 我猜它将新行计为 1,tab 计为 2nd,然后 k 计为 3rd ;)
  • 我该如何解决? @BilboBaggins
  • 尝试创建一个集合/映射或其他一些数据结构来保存您不想计算的所有关键字/单词,或者另一种方法是从您的首先是字符串,然后从中查找单词。
  • 特别是在下面的示例中,它给出了 3 而不是 2 好的。这三个元素的价值是什么?是[, \n, k] 吗? \n 之前有空行吗?是\n[tab][newLine][tab]k 吗?

标签: java string file bufferedreader filereader


【解决方案1】:

我猜第二行被分成两个字符串,“”和“k”。请看下面的代码:

import java.util.Arrays;

public static void main(String[] args) {
    String str = "           k";
    String[] array = str.split("\\\s+");
    System.out.println("length of array is " + array.length); // length is 2
    System.out.println(Arrays.toString(array)); //array is [, k]
}

【讨论】:

    【解决方案2】:

    如果您使用的是 Java 8,则可以使用 Streams 并过滤您认为是“单词”的内容。例如:

        List<String> l = Files.lines(Paths.get("files/input.txt")) // Read all lines of your input text
                .flatMap(s->Stream.of(s.split("\\s+"))) // Split each line by white spaces
                .filter(s->s.matches("\\w")) // Keep only the "words" (you can change here as you want)
                .collect(Collectors.toList()); // Put the stream in a List
    

    在这种特定情况下,它将输出[k]

    您当然可以在 Java 7 中执行相同的操作,方法是调整您的代码并将此条件添加到您的 for 循环中:

    if(strArray[i].matches("\\w"))
        strList.add(strArray[i]); // Keep only the "words" - again, use your own criteria
    

    只是比较麻烦。

    希望对你有帮助。

    【讨论】:

    • 为什么要把流拖到这么简单的问题上?
    • 文件是行流,行是词流。无需使用BufferedReaderFileReader 或进行显式循环。结果更短,更易读。
    • 但是您将整个文件读入内存。如果文件很大,逐行读取会更好。你的代码会消耗更多的内存。
    猜你喜欢
    • 1970-01-01
    • 2021-01-19
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2012-06-13
    • 2016-08-10
    相关资源
    最近更新 更多