字符统计

这次实验主要是针对文本中单词的读取,主要用到了以下知识:

Bufferedreader类实现文本读入,拆分,String类下的split函数实现单词分割。

建立Map类,实现统计功能。

不排序时使用迭代器进行输出,排序时使用List接口,再使用Collections下的sort函数进行排序,利用循环进行遍历输出

List是一个接口,ArrayList是一个类,面向接口编程;

文件的读入,文件转化为文字,再把文字缓冲读入;

代码:

import java.io.*;
import java.util.*;
public class treat {

    public static void main(String[] args) {
        Map<String,Integer> map=new HashMap<String,Integer>();
        try {
            File file=new File("/Users/lgh/Desktop/horrypotter.txt");
            BufferedReader read=new BufferedReader(new FileReader(file));
            String str;
            while((read.readLine())!=null) {
                str=read.readLine();
                String[] strsplit=str.split("\\W+");
                for(int i=0;i<strsplit.length;i++) {
                    if(map.containsKey(strsplit[i])) {
                        int a;
                        a=map.get(strsplit[i]);
                        map.put(strsplit[i],a+1);
                    }else {
                        map.put(strsplit[i],1);
                    }
                }
            }
            Iterator<Map.Entry<String,Integer>> iterator=map.entrySet().iterator();
            double qwe=map.size();
            /*while(iterator.hasNext()) {
                Map.Entry<String,Integer> entry=iterator.next();
                System.out.printf("%s:%d  %.2f\n",entry.getKey(),entry.getValue(),entry.getValue()/qwe);
            }*/
        }
        catch(Exception e){
            System.err.println(e);
        }
        List<Map.Entry<String,Integer>> list=new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>(){
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        for(Map.Entry<String,Integer> a:list){
            System.out.println(a.getKey()+":"+a.getValue());
        }

    }

}
posted @ 2020-01-01 15:00  林某大帅比  阅读(166)  评论(0编辑  收藏  举报