【问题标题】:How to count sentences printed out from text file?如何计算从文本文件中打印出来的句子?
【发布时间】:2018-02-21 15:44:42
【问题描述】:

我目前有这个类可以打印出所有包含单词“Goal”或“goal”的句子。我想知道有没有一种方法可以计算打印出多少个句子?该类读取Results.txt并打印出包含“Goal”或“goal”的两个句子。如何实现计算句子并返回数字二的方法。

    public static void main(String args[])
    {
        try{
              // Open the file that is the first 
              // command line parameter
              FileInputStream fstream = new FileInputStream("src\\sentiment\\Results.txt");
              // Get the object of DataInputStream
              DataInputStream in = new DataInputStream(fstream);
              BufferedReader br = new BufferedReader(new InputStreamReader(in));
              String strLine;

              //Read File Line By Line
              while ((strLine = br.readLine()) != null)    
              {
                  if(strLine.contains("goal") || strLine.contains("Goal"))
                  // Print the content on the console
                  System.out.println(strLine);
              }
              //Close the input stream
              in.close();
              }

        catch (Exception e)
        {//Catch exception if any
              System.err.println("Error: " + e.getMessage());
        }
 }

【问题讨论】:

  • 什么是句子?单线?从..!??
  • 您当前的设置包含 main 方法中的所有内容。最简单的解决方案是添加一个局部变量,每当您的if 语句中的行包含目标或目标时,该变量就会递增。如果这对您不起作用,您必须传递整个字符串来重新计算似乎有点多余的数据。
  • 一个句子就是每一个新的一行。

标签: java count counter fileinputstream datainputstream


【解决方案1】:

如果您只想计算匹配的行数,只需增加一个计数器并在完成后打印它:

              // Initialize the counter
              int count = 0;

              // Read File Line By Line
              while ((strLine = br.readLine()) != null)    
              {
                  if(strLine.contains("goal") || strLine.contains("Goal")){

                      // Print the content on the console
                      System.out.println(strLine);
                      // Increment the counter
                      count++;

                  }

              }

              // Print the total
              System.out.println(count);

【讨论】:

  • 谢谢。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
  • 1970-01-01
  • 2021-08-11
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
相关资源
最近更新 更多