zoukankan      html  css  js  c++  java
  • 统记字母个数以及所占百分比排序输出

    设计思路:

    首先读入文件,将读入内容存放至一个字符数组中,将大写字符转换为小写,小写字母不变;

    运用HashMap类进行计数:对字符串数组中的元素进行比较,并且对相同元素的个数,每一个不同的元素进行记录,最后将结果输出。

    源代码:

    package text;
    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;
    public class TongJiDanCi {
     public static void main(String[] args)throws IOException//扔掉很重要
     {
       File file = new File("D:/yingwen.txt");
          txtString(file); 
          
     }
     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<String, Integer>();//构建了一个新的HashMap对象,强制指定这个HashMap必须是以String为key, 以Integer为值。
       String line =null;
       Integer count = 0;//每个字母的个数
       Integer total = 0;//统计字母总数,作百分比用
       while ((line=br.readLine())!=null) {
        char[] ch = line.toCharArray();//将字符串对象中的字符转换为一个字符数组。
        total = total + ch.length;
        for (int i = 0; i < ch.length; i++) {
         ch[i] = Character.toLowerCase(ch[i]);//将大写字符转换为小写,小写字母不变
         count = hm.get(ch[i]+"");//ch[i]+""的作用是加一个空格后,括号内转化为字符串
         if (count == null) {
          count =1;//只出现一次
         }else {
          count++;
         }
         hm.put(ch[i]+"", count);
        }
       }
       for (String str : hm.keySet()) {//设变量str获取键
        System.out.println(str+"个数:"+hm.get(str)+"  "+hm.get(str)*100.0/total+"%");
       }
       System.out.println("总字母个数:"+total);
       /*
        * 排序输出
        */
        List<Map.Entry<String,Integer>> list_Data = new ArrayList<Map.Entry<String,Integer>>(hm.entrySet()); 
           Collections.sort(list_Data, new Comparator<Map.Entry<String,Integer>>(){  
                 public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) 
                 { 
                 //o1 to o2升序   o2 to o1降序
                 return o2.getValue().compareTo(o1.getValue());
                 } 
             }); 
           System.out.println("排序输出:");
           System.out.println(hm);
       
      } catch (FileNotFoundException e) {
       e.printStackTrace();
      }
     }
    }

     运行结果:

  • 相关阅读:
    linux机器间建立信任关系
    Linux shell逐行读取文件的方法
    linux强制用户下线命令
    Linux用户都应该了解的命令行省时技巧
    常用Linux Shell命令组合
    利用TensorFlow object_detection API 训练自己的检测器
    逻辑回归的梯度下降计算
    Android内存优化(使用SparseArray和ArrayMap代替HashMap)
    卷积的三种模式:full、same、valid + 卷积输出size的计算
    关于转置卷积(反卷积)的理解
  • 原文地址:https://www.cnblogs.com/sengzhao666/p/10786073.html
Copyright © 2011-2022 走看看