统计文件中单词出现的频次

public class Util{
    public static void main(String[] args) throws IOException {
        //键盘录入指定文件名
        Scanner sc = new Scanner(System.in);
        String fileName = sc.nextLine();

        //调用方法,求结果
        countWord(fileName);
    }

    public static void countWord(File filename) throws IOException {
        Util util = new Util();
        String[] str = util.readFile(filename);
        Map<String,Integer>  map = new  HashMap<String,Integer>();
        //遍历数组(即整篇文章)
        for(String word : str){
            if(map.containsKey(word)){
                //包含该单词则加1
                map.put(word, map.get(word)+1);
            }else{
                //第一次出现则为1
                map.put(word, 1);
            }
        }
        util.printCount(map);
      }
 
    public  String[] readFile(File filename) throws IOException {
        Reader reader = new FileReader(filename);
        //BufferedReader可以读取行,读取速度快
        BufferedReader br = new BufferedReader(reader);
        //用于将读取的每一句拼接,去除边缘截断单词
        StringBuffer sbu = new StringBuffer();
        String line = "";
        while (null != (line = br.readLine())) {
            //拼接行
            sbu.append(line);
        }
        // System.out.println(sbu);
        String s = sbu.toString();
        //正则中的非英文字符分割
        String[] str = s.split("\\W");
        return str;
    }

    //打印方法
    public  void printCount(Map map) {
         Set<String> set = map.keySet();
         for (String key : set) {
          String str = key + "——>" + map.get(key);
          System.out.println(str);
          }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值