我需要根据此代码计算文件的每个句子中有多少个单词 我们有一个名为 archivo 的文件:
File archivo = null;
try {
archivo = new File("Text.txt");
String line;
FileReader fr = new FileReader (archivo);
BufferedReader br = new BufferedReader(fr);
int i,a=0;
while((linea=br.readLine())!=null) {
for(i=0;i<line.length();i++){
if(i==0){
if(line.charAt(i)!=' ')
a++;
}else{
if(line.charAt(i-1)==' ')
if(line.charAt(i)!=' ')
a++;
}
}
}
这里我们打印单词数,但我还需要每个句子的单词数
System.out.println("There are "+a+" words");
fr.close();
}catch(IOException a){
System.out.println(a);
}
}
}
text.txt 说:
嗨 我是凯蒂 我有两只猫。
最佳答案
按如下方式进行:
String line;
int count=0, totalCount=0;
while((line=br.readLine())!=null) {
count = line.split("\\s+").length;
System.out.println("The number of words in '" + line + "' is: " + count);
totalCount += count;
}
System.out.println("The total number of words in the file is " + count);
说明: String::split函数根据指定的正则表达式将字符串拆分为字符串数组。正则表达式 \\s+
表示一个或多个空格。对于每一行,程序都会打印 count
,即单词数(即拆分发生后生成的数组的长度),并将其添加到 totalCount
中。最后,程序打印totalCount
(文件中的总字数)。
关于java - 基于此Java代码的文件的每个句子中有多少个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60830998/