如何计算从文本文件打印出的句子



我当前有此类,它打印出包含"目标"或"目标"一词的所有句子。我想知道有什么方法可以计算出多少个句子?班级读取结果。txt并打印出包含"目标"或"目标"的两个句子。我如何实现一种将句子计算并返回二的方法。

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

如果您只想计算匹配行,只需增加计数器并打印一旦完成:

              // 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);

相关内容

  • 没有找到相关文章

最新更新