文本harry potter的字符统计

实现计算文件中字符的占比和不同单词的个数两项功能,首先将文本文件按行导入到程序中,再通过charAT()函数来实现对单个字符的操作,并用集合来统计字符总数以及不同的字符的个数,进而输出各个字符的个数以及占总数的百分比。计算单词个数时通过判断是否是非单词字符来实现,并使用sort()函数来实现升序操作。通过循环输出单词及其个数。

package All;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class all {
    public static void main(String[] args)throws IOException//扔掉很重要
    {
         File file = new File("f.txt");
         System.out.println("1.统计英文单词个数"+"  "+"2.统计字母个数");
         Scanner sc = new Scanner(System.in);
         int value=sc.nextInt();
      
         switch(value) {
            
                  case 1:txtString2(file);
                         break;
                  case 2:txtString(file);break;
                 
         }
         }
  
    
    
    
    /*
     * 统计字母
     */
    public static void txtString(File file) throws IOException{
        try {
            //IO操作读取文件内容
            FileReader fr = new FileReader(file);
            @SuppressWarnings("resource")
            BufferedReader br = new BufferedReader(fr);//构造一个BufferedReader类来读取文件        
            HashMap<String,Integer> hm = new HashMap<>();//构建了一个新的HashMap对象,强制指定这个HashMap必须是以String为key, 以Integer为值。 
            String line =null;
            Integer count = 0;//每个字母的个数
            Integer total = 0;//统计字母总数,作百分比用
            char ch;
            while ((line=br.readLine())!=null) {
                for(int j=0;j<line.length();j++) {
                	 ch=line.charAt(j); 
                   if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')) {//将字符串对象中的字符转换为一个字符数组。
                  total = total + 1;
               
            	    count=hm.get(ch+"");
            	   if(count==null) {
            		   count=1;
            	   }
            	   else {
            		   count++;
            	   }
            	   hm.put(ch+"",count); 
                   }
                }
            }
            /*
            
            for (String str : hm.keySet()) {//设变量str获取键
            	lv=list.get(list.size()-i-1).getValue()*1.0/total*100;
                System.out.println(str+"个数:"+hm.get(str)+"        "+String.format("%.2f", lv)+"%");   
            }*/
            System.out.println("总字母个数:"+total);
            
            List<Map.Entry<String ,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(hm.entrySet());
          //在java中,如果要对集合对象或数组对象进行排序,需要实现Comparator接口以达到我们想要的目标
                  Comparator<Map.Entry<String,Integer>> comparator = new Comparator<Map.Entry<String, Integer>>() {
                      public int compare(Map.Entry<String, Integer> left, Map.Entry<String, Integer> right) {
                          return (left.getValue().compareTo(right.getValue()));
                      }
                  };
                  // 集合默认升序升序
                  Collections.sort(list,comparator);
                  double lv=0;
                  for(int i=0;i<52;i++){// 由高到低输出
                	  lv=list.get(list.size()-i-1).getValue()*1.0/total*100;
                      System.out.println(list.get(list.size()-i-1).getKey() +":"+list.get(list.size()-i-1).getValue()+"    "+String.format("%.2f", lv)+"%");
                  }
            

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    
    
    /*
     * 统计单词
     */
     public static void txtString2(File file)  throws IOException{
         FileReader fr = new FileReader(file);
         BufferedReader br = new BufferedReader(fr);//构造一个BufferedReader类来读取文件    
         StringBuffer sb = new StringBuffer();
         String line =null;
         while ((line=br.readLine())!=null){
            sb.append(line);//将读取出的字符追加到stringbuffer中
        }     
        fr.close();
       // 关闭读入流
             String str = sb.toString().toLowerCase(); // 将stringBuffer转为字符并转换为小写
             String[] words = str.split("[^(a-zA-Z)]+");  // 非单词的字符来分割,得到所有单词
             Map<String ,Integer> map = new HashMap<String, Integer>() ;
             for(String word :words){
                 if(map.get(word)==null){  // 若不存在说明是第一次,则加入到map,出现次数为1
                     map.put(word,1);
                 }else{
                     map.put(word,map.get(word)+1);  // 若存在,次数累加1
                 }
             }
             // 排序
            List<Map.Entry<String ,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
             Comparator<Map.Entry<String,Integer>> comparator = new Comparator<Map.Entry<String, Integer>>() {
                 public int compare(Map.Entry<String, Integer> left, Map.Entry<String, Integer> right) {
                  int i=left.getValue()-right.getValue();
                     if(i==0) {
                      return (right.getKey().compareTo(left.getKey()));
                     }
                     return (left.getValue().compareTo(right.getValue()));
                 }
             };
           
             // 集合默认升序
             Collections.sort(list,comparator);
             int n=list.size();
             
             System.out.println("一共有"+n+"个单词");
           
             for(int i=0;i<n;i++){// 由高到低输出
                 System.out.print(list.get(list.size()-i-1).getKey() +":"+list.get(list.size()-i-1).getValue()+"  ");
             }
     }
     
    
}

  结果截图:

 

猜你喜欢

转载自www.cnblogs.com/lijiawei1-2-3/p/11802259.html