繁体   English   中英

基于此代码Java的文件的每个句子中有多少个单词

[英]How many words are in each sentence of the file based in this code Java

我需要根据此代码计算文件的每个句子中有多少个单词我们有一个名为 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 (文件中的总字数)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM