gpt4 book ai didi

java - 如何统计从文本文件打印出来的句子数?

转载 作者:行者123 更新时间:2023-12-01 19:57:49 25 4
gpt4 key购买 nike

我目前有这个类,可以打印出包含单词“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());
}
}

最佳答案

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

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

关于java - 如何统计从文本文件打印出来的句子数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48909952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com