fileStatistics-麻烦计算文件中的单词数



在我的课程中,我们的任务是确定通过控制台输入传递的文件的三个关键统计信息:1)字符数,2)行数,3)3)字。在以重复的方式关闭此问题之前,请继续阅读以查看我遇到的独特问题。谢谢:)

我最初用三种单独的方法和三个独立的扫描仪变量编写了一个解决方案,但是我意识到,对于较大的文件,该解决方案将非常低效。取而代之的是,我决定编写一个仅在文件中运行的解决方案,并一次计算所有三个统计信息。这是我到目前为止所拥有的:

import java.util.*;
import java.io.*;

public class FileStatistics
{   
    // Note: uncomment (A) and (B) below to test execution time
    public static void main( String [] args ) throws IOException
    {
        /* (A)
        long startTime = System.currentTimeMillis();
        */
        File file = new File(args[0]);
        Scanner input = new Scanner(file);
        int numChars = 0, numWords = 0, numLines = 0;

        /* Calculations */
        while( input.hasNextLine() )
        {
            String currentLine = input.nextLine();
            numLines++;
            numChars+= currentLine.length();
            String [] words = currentLine.split(" ");
            numWords += words.length;               
        }
        input.close();

        /* Results */
        System.out.println( "File " + file.getName() + " has ");
        System.out.println( numChars + " characters");
        System.out.println( numWords + " words");
        System.out.println( numLines + " lines");

        /* (B) 
        long endTime = System.currentTimeMillis();
        System.out.println("Execution took: " + (endTime-startTime)/1000.0 + " seconds");
        */
    }

}


我一直在将程序的结果与Microsoft Word自己的文件统计信息进行比较,只需复制/粘贴我使用的任何文件的内容。正确计算字符的数量和行数。

但是,我的程序无法正确计算单词数。我决定在其中包括一个测试语句以打印出数组words的内容,并且似乎某些"空间格式"(例如Java源代码文件中的TABS)被视为拆分数组中的单个元素。在调用拆分方法以删除这些选项卡之前,我尝试执行currentLine.replace("t", ""),但这并没有改变。

有人可以为我做错了什么建议或提示吗?

这是因为currentLine.split(" ")返回的字符串数组可以包含空字符串的元素:""。如果您致电System.out.println(Arrays.toString(words))

,您可以看到此

要创建所需的行为,您可以将words.length存储在变量count中,并为words中的空字符串""的每个实例降低count

这是一个示例解决方案:

while( input.hasNextLine() )
{
    String currentLine = input.nextLine();
    numLines++;
    numChars+= currentLine.length();
    String [] words = currentLine.split("\s+");
    int count = words.length;
    for (int i = 0; i < words.length; i++) {
        if (words[i].equals("")) {
            count--;
        }
    }
    numWords += count;
}

另外,您可以将words转换为ArrayList并使用removeAll()功能:

while( input.hasNextLine() )
{
    String currentLine = input.nextLine();
    numLines++;
    numChars+= currentLine.length();
    ArrayList<String> words = new ArrayList<>(Arrays.asList(currentLine.split("\s+")));
    words.removeAll(Collections.singleton(""));
    numWords += words.size();
}

最新更新