如何用java代码实现查询一段话中每个单词出现的次数

如何用java代码实现查询一段话中每个单词出现的次数

package com.xdl;
import java.util.*;

public class Homework {
    public static void main(String[] args) {
        String ss = "Mr. Louis P. Barker of northern Iowa was also on the car, and he\n" +
                "described a cyclone that he saw in the '70s along in September at the\n" +
                "close of a hot but clear day. The first intimation that Mr. Barker had\n" +
                "of an approaching storm was a small cloud no larger than a man's hand\n" +
                "which he discovered moving slowly toward the southwest with a gyratory\n" +
                "movement. It then appeared to be a funnel-shaped cloud which passed\n" +
                "along near the surface of the ground with its apex now and then lightly\n" +
                "touching a barn or a well, and pulling it out by the roots. It would\n" +
                "then bound lightly into the air and spit on its hands. What he noticed\n" +
                "most carefully on the following day was the wonderful evidences of its\n" +
                "powerful suction. It sucked a milch cow absolutely dry, pulled all the\n" +
                "water out of his cistern, and then went around to the waste-water pipe\n" +
                "that led from the bath-room and drew a 2-year-old child, who was taking\n" +
                "a bath at the time, clear down through the two-inch waste-pipe, a\n" +
                "distance of 150 feet. He had two inches of the pipe with him and a lock\n" +
                "of hair from the child's head.";
        String regex = "[\\s\\p{Punct}]+";
        ss = ss.toLowerCase();
        //System.out.println(ss);
        String words[]=ss.split(regex);
        Map<String,Integer>map = new HashMap<String, Integer>();
        for (int i = 0;i<words.length;i++){
            //map.get(),通过键名来获取键值
            if (map.get(words[i]) == null){
                //map.put()将键值存储在map集合中,如果存在,那么就覆盖该键值,如果不存在就新建一个。
                map.put(words[i],1);
            }else {
                int frequency = map.get(words[i]);
                map.put(words[i],++frequency);
            }
        }
        Set <Map.Entry<String,Integer>> entrys = map.entrySet();
        Iterator<Map.Entry<String,Integer>> it = entrys.iterator();
        while(it.hasNext()){
            Map.Entry<String,Integer> entry = it.next();
            System.out.println(entry.getKey()+"   出现 "+entry.getValue()+" 次");
        }

    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值