随笔 - 355  文章 - 0  评论 - 3  阅读 - 63043

java读取文件并统计出现前N个单词

Java文件操作---输出单个文件中常出现的前N个英语单词 - 千幽行 - 博客园 (cnblogs.com)

复制代码
package classtest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeMap;

public class liu {
    public static void main(String[] args) {
        //读取文件
        File file=new File("D:\\javaidea\\work\\classtest01\\wenjian\\HP7.txt");
        Scanner in=new Scanner(System.in);
        try {
            FileReader fr = new FileReader(file);
            BufferedReader bufr = new BufferedReader(fr);
            //按行读取返回的字符串
            String s = null;
            //将所有s字符串拼接
            String all = null;
            while((s=bufr.readLine())!=null){
                all = all + s;
            }
            //定义TreeMap
            Map<String,Integer> tm = new TreeMap<>();
            //按找非数字字母符号分割字符串,组成字符串数组
            String[]strs = all.split("[^a-zA-Z0-9]");
            //用于存放字符串的数组
            String[]r1=new String[strs.length];
            //用于存放字符串出现次数的数组
            int[]r2=new int[strs.length];
            //读取分割后的字符串数组,使用TreeMap存入字符串(key)及其出现次数(value)
            for(int i = 0; i < strs.length; i++){
                strs[i].toLowerCase();
                if(!tm.containsKey(strs[i])){
                    tm.put(strs[i], 1);
                }else{
                    Integer counts = tm.get(strs[i]);
                    tm.put(strs[i], counts+1);
                }
            }
            int j=0;
            //遍历TreeMap,摘取key和value,分别存入事先构建好的数组(foreach)
            for(Entry<String,Integer>entry:tm.entrySet()) {
                r1[j]=entry.getKey();
                r2[j]=entry.getValue();
                j++;
            }
            //冒泡降序排序
            for(int p=0;p<strs.length-1;p++) {
                for(int q=0;q<strs.length-1-p;q++) {
                    if(r2[q]<r2[q+1]) {
                        int temp=r2[q];
                        r2[q]=r2[q+1];
                        r2[q+1]=temp;
                        String tems=r1[q];
                        r1[q]=r1[q+1];
                        r1[q+1]=tems;
                    }
                }
            }
            int l=in.nextInt();
            //存储完成后的数组首元素非字符串(:r2[0]),未能成功消去所以从第二个开始输出。
            for(int i=1;i<l+1;i++) {
                System.out.println(r1[i]+":"+r2[i]);
            }
            //关闭
            in.close();
            bufr.close();
            fr.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}
复制代码

 

posted on   201812  阅读(51)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示