文件结构:
运行截图:
实现代码:
1 package Ape; 2 3 import java.io.*; 4 import java.util.regex.Matcher; 5 import java.util.regex.Pattern; 6 7 public class CountPlus2 { 8 9 public static void output(String filepath) { //输出实现部分 10 String temp=null; 11 Pattern pattern=Pattern.compile("[^a-zA-Z]"); //匹配非字母 12 Pattern pattern1=Pattern.compile("^[a-zA-Z]{3,}"); //剔除无意义单词如:is,a,at等 13 String []ape=new String[10000]; //存储单词 14 int []num=new int[10000];//存储数量 15 int count=0; //记录多少个不同的单词,即ape数组的长度 16 File file=new File(filepath);//导入文件 17 try { 18 FileReader reader=new FileReader(file); 19 BufferedReader br=new BufferedReader(reader); 20 try { 21 while((temp=br.readLine())!=null) //读取到结尾时停止 22 { 23 Matcher matcher=pattern.matcher(temp); //匹配字符串 24 if(matcher.find()) 25 temp=matcher.replaceAll(" "); //替换字符串 26 String str[]=temp.toLowerCase().trim().split(" "); //分割字符串 27 if(str.length>0) { //如果字符串中有单词 28 for(int j=0;j<str.length;j++) { 29 Matcher matcher1=pattern1.matcher(str[j]); //剔除无意义单词 30 if(count==0) { 31 ape[count]=str[j]; 32 num[count]++; 33 count++; 34 } 35 else if(matcher1.find()){ //进行计数 36 int tempnum=count; 37 for(int k=0;k<tempnum;k++) { 38 if(ape[k].equals(str[j])) 39 { 40 num[k]++; 41 break; 42 } 43 else if(k==tempnum-1){ 44 ape[count]=str[j]; 45 num[count]++; 46 count++; 47 } 48 } 49 } 50 } 51 } 52 } 53 } catch (IOException e) { 54 // TODO Auto-generated catch block 55 e.printStackTrace(); 56 } 57 } catch (FileNotFoundException e) { 58 // TODO Auto-generated catch block 59 e.printStackTrace(); 60 } 61 for(int i=0;i<count;i++) //冒泡排序法实现倒序排序 62 for(int j=0;j<count-1-i;j++) 63 { 64 int numtemp; 65 String tempch; 66 if(num[j]<num[j+1]) 67 { 68 numtemp=num[j];num[j]=num[j+1];num[j+1]=numtemp; 69 tempch=ape[j];ape[j]=ape[j+1];ape[j+1]=tempch; 70 } 71 } 72 for(int i=0;i<count;i++) { //输出单词以及对应数量 73 System.out.println(ape[i]+" "+num[i]); 74 } 75 } 76 77 78 public static void handle(String filepath) { //递归实现部分 79 File file=new File(filepath); //绝对路径创建文件对象 80 if(file.isDirectory()) { //判断是否有子目录 81 File strfile[]=file.listFiles(); //进行子目录分割 82 for(int i=0;i<strfile.length;i++) //遍历子目录输出 83 { 84 handle(strfile[i].getAbsolutePath()); //进行递归 85 } 86 }else //如果没有子目录则输出文件名以及统计单词数量 87 { 88 System.out.println("*********"+file.getName()+"*********"); 89 output(file.getAbsolutePath()); 90 } 91 } 92 public static void main(String[] args) { 93 // TODO Auto-generated method stub 94 File file=new File("1"); 95 handle(file.getAbsolutePath()); 96 } 97 98 }