【问题标题】:Counting number of lines, words, and characters in a text file计算文本文件中的行数、单词数和字符数
【发布时间】:2013-02-20 18:33:20
【问题描述】:

我正在尝试从用户那里获取输入,并打印文本文件中的行数、单词数和字符数。但是,只有字数是正确的,它总是为行和字符打印 0。

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

public class TextFileInfoPrinter
{  
    public static void main(String[]args) throws FileNotFoundException        
    { 
            Scanner console = new Scanner(System.in);           

            System.out.println("File to be read: ");
            String inputFile = console.next();

            File file = new File(inputFile);
            Scanner in = new Scanner(file);

            int words = 0;
            int lines = 0;
            int chars = 0;

            while(in.hasNext())
            {
                in.next();
                words++;
            }

            while(in.hasNextLine())
            {
                in.nextLine();
                lines++;
            }

            while(in.hasNextByte())
            {
                in.nextByte();
                chars++;
            }

            System.out.println("Number of lines: " + lines);
            System.out.println("Number of words: " + words);
            System.out.println("Number of characters: " + chars);
    }
}

【问题讨论】:

    标签: java file input


    【解决方案1】:

    试试

        int words = 0;
        int lines = 0;
        int chars = 0;
        while(in.hasNextLine())  {
            lines++;
            String line = in.nextLine();
            chars += line.length();
            words += new StringTokenizer(line, " ,").countTokens();
        }
    

    【讨论】:

    • 好,注意我们可以用不同的方式计算单词,我使用','和''作为单词分隔符,但是你可以改变它
    【解决方案2】:

    in.next(); 正在消耗第一个 while() 中的所有行。在第一个 while 循环结束后,输入流中不再有要读取的字符。

    你应该嵌套你的字符和字数计数一个while循环计数行。

    【讨论】:

      【解决方案3】:

      你认为有什么原因吗:

      while(in.hasNext())
      {
          in.next();
          words++;
      }
      

      不会消耗整个输入流吗?

      这样做,这意味着您的另外两个while 循环将永远不会迭代。这就是为什么您的单词和行的值仍然设置为零的原因。

      您最好一次读取文件一个字符,每次循环增加字符数,并检测字符以决定是否增加其他计数器。

      基本上,无论您在哪里找到 \n,都增加行数 - 如果流中的最后一个字符不是 \n,您可能也应该这样做。

      而且,每当您从空白过渡到非空白时,请增加字数(在流开始时可能会有一些棘手的边缘情况处理,但这是一个实现问题)。

      您正在查看类似于以下伪代码的内容:

      # Init counters and last character
      
      charCount = 0
      wordCount = 0
      lineCount = 0
      lastChar = ' '
      
      # Start loop.
      
      currChar = getNextChar()
      while currChar != EOF:
          # Every character counts.
      
          charCount++;
      
          # Words only on whitespace transitions.
      
          if isWhite(lastChar) && !isWhite(currChar):
              wordCount++
      
          # Lines only on newline characters.
      
          if currChar == '\n':
              lineCount++;
          lastChar = currChar
          currChar = getNextChar()
      
      # Handle incomplete last line.
      
      if lastChar != '\n':
          lineCount++;
      

      【讨论】:

        【解决方案4】:

        我认为最好的答案是

        int words = 0;
        int lines = 0;
        int chars = 0;
        while(in.hasNextLine())  {
            lines++;
            String line = in.nextLine();
           for(int i=0;i<line.length();i++)
            {
                if(line.charAt(i)!=' ' && line.charAt(i)!='\n')
                chars ++;
            }
            words += new StringTokenizer(line, " ,").countTokens();
        }
        

        【讨论】:

          【解决方案5】:

          在执行第一个 while 时,文件指针设置为文件末尾。试试这个:

          Scanner in = new Scanner(file);
          
          
                  while(in.hasNext())
                  {
                      in.next();
                      words++;
                  }
                  in = new Scanner(file);
                  while(in.hasNextLine())
                  {
                      in.nextLine();
                      lines++;
                  }
                  in = new Scanner(file);
                  while(in.hasNextByte())
                  {
                      in.nextByte();
                      chars++;
                  }
          

          【讨论】:

          • 嵌套它会有自己的问题。条件需要改变。
          【解决方案6】:

          我不是 Java 专家,但我认为 .hasNext.hasNextLine.hasNextByte 都使用和递增相同的文件位置指示器。您需要重置它,方法是创建一个 Aashray 提到的新扫描器,或者使用 RandomAccessFile 并在每次循环后调用 file.seek(0);

          【讨论】:

            【解决方案7】:

            我同意@Cthulhu 的回答。在您的代码中,您可以重置您的 Scanner 对象 (in)。

            in.reset();
            

            这将在文件的第一行重置您的 in 对象。

            【讨论】:

              【解决方案8】:

              您可以使用正则表达式为您计数。

              String subject = "First Line\n Second Line\nThird Line";  
              Matcher wordM = Pattern.compile("\\b\\S+?\\b").matcher(subject); //matches a word
              Matcher charM = Pattern.compile(".").matcher(subject); //matches a character
              Matcher newLineM = Pattern.compile("\\r?\\n").matcher(subject); //matches a linebreak
              
              int words=0,chars=0,newLines=1; //newLines is initially 1 because the first line has no corresponding linebreak
              
              while(wordM.find()) words++;
              while(charM.find()) chars++;
              while(newLineM.find()) newLines++;
              
              System.out.println("Words: "+words);
              System.out.println("Chars: "+chars);
              System.out.println("Lines: "+newLines);
              

              【讨论】:

                【解决方案9】:
                while(in.hasNextLine())  {
                        lines++;
                        String line = in.nextLine();
                        for(int i=0;i<line.length();i++)
                        {
                            if(line.charAt(i)!=' ' && line.charAt(i)!='\n')
                        chars ++;
                        }
                        words += new StringTokenizer(line, " ,;:.").countTokens();
                    }
                

                【讨论】:

                  【解决方案10】:
                  import java.io.*;
                  class wordcount
                  {
                      public static int words=0;
                      public static int lines=0;
                      public static int chars=0;
                      public static void wc(InputStreamReader isr)throws IOException
                      {
                          int c=0;
                          boolean lastwhite=true;
                          while((c=isr.read())!=-1)
                          {
                              chars++;
                              if(c=='\n')
                                  lines++;
                              if(c=='\t' || c==' ' || c=='\n')
                                  ++words;
                              if(chars!=0)
                                  ++chars;
                          }   
                         }
                      public static void main(String[] args)
                      {
                          FileReader fr;
                          try
                          {
                              if(args.length==0)
                              {
                                  wc(new InputStreamReader(System.in));
                              }
                              else
                              {
                                  for(int i=0;i<args.length;i++)
                                  {
                                      fr=new FileReader(args[i]);
                                      wc(fr);
                                  }
                              }
                  
                          }
                          catch(IOException ie)
                          {
                              return;
                          }
                          System.out.println(lines+" "+words+" "+chars);
                      }
                  }
                  

                  【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2018-06-02
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2023-03-12
                  • 1970-01-01
                  相关资源
                  最近更新 更多