如何用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()+" 次");
}
}
}