用Java创建一个计算句子,段落,字母和单词的程序

时间:2018-12-03 21:13:24

标签: java

我需要创建一个程序,该程序计算文本文件中字符的频率以及单词和句子的段落数。

我有一个问题,当我的程序输出字母频率时,程序会为字母表中的每个字母输出多个输出。

输出应如下所示:

如果输入的是“你好,世界!”

(应为字母表中的所有字母输出):

  

找到字母a 0次

     

字母b被发现0次

(直到到达出现的字母,然后显示出现的次数)

  

段落数:1

     

句子数:1

     

字符数:10

     

字数:2

我已经为此工作了几周,但仍然找不到解决方案。

package SuperCounter2;

import java.io.*;

public class SuperCounter2 {

public static void main(String[] args) throws IOException {
    File file = new File("//Users//4617621//Desktop//This is the most stupid assignment");
    FileInputStream fileStream = new FileInputStream(file);
    InputStreamReader input = new InputStreamReader(fileStream);
    BufferedReader reader = new BufferedReader(input);

    String line;

    int countWord = 0;
    int sentenceCount = 0;
    int characterCount = 0;
    int paragraphCount = 1;
    int whitespaceCount = 0;

    while ((line = reader.readLine()) != null) {
        int ci, i, j, k, l = 0;
        char c, ch;
        i = line.length();

        if (line.equals("")) {
            paragraphCount++;
        }

        if (!(line.equals(""))) {
            characterCount += line.length();

            String[] wordList = line.split("\\s+");

            countWord += wordList.length;
            whitespaceCount += countWord - 1;

            String[] sentenceList = line.split("[!?.:]+");
            sentenceCount += sentenceList.length;
        }

         int counter = 0;

        for (int m = 0; m < line.length(); m++) {
            counter++;
        }

        for (c = 'A'; c <= 'z'; c++) {
            k = 0;
            for (j = 0; j < i; j++) {
                 ch = line.charAt(j);
            if(ch == c) {
                k++;
                  System.out.println(" the character " + c + " has occured " + k + " times");
            }
        }
    }
  }

   System.out.println("Total word count = " + countWord);
    System.out.println("Total number of sentences = " + sentenceCount);
    System.out.println("Total number of characters = " + characterCount);
    System.out.println("Number of paragraphs = " + paragraphCount);
    System.out.println("Total number of whitespaces = " + whitespaceCount);

  }
}

1 个答案:

答案 0 :(得分:1)

我认为您可以将其视为简单地计算周期,空格,回车等的次数。

通过一次带一个字母而不是一个单词来实现此目的可能会更容易。

唯一可能棘手的地方(您需要一次查看多个事物)是“ word1.word2”,“ word1.word2”或“ word1.word2”(两个)的情况空格)。对于那些字符,您可能必须保留一个标志,如果前一个字符是“单词分隔符”(句点,空格,c / r),则不要再计算另一个单词。

否则,这似乎很简单。查看字符,如果是句点,则将其添加到行数和单词数中;如果是空格,则将其添加到字数中;如果是ac / r,则将其添加到段落中,并添加字数,然后跟踪每个字母(可能在地图上)

如果算上标志操作,循环的内部应该大约有5行代码。

不写代码,因为这听起来像是作业。

PS:实际上这似乎是一个很酷的任务:)