繁体   English   中英

计算文本文件中的行数,单词数和字符数

[英]Counting number of lines, words, and characters in a text file

我试图从用户那里获取输入,并在文本文件中打印行数,单词和字符。 但是,只有单词的数量是正确的,它总是为行和字符打印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);
    }
}

尝试

    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();
    }

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

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

你认为有什么理由:

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++;

我认为最好的答案是

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();
}

执行第1个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++;
        }

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

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

in.reset();

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

您可以使用正则表达式来计算您的数量。

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);
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();
    }
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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM