词频统计设计
需求概要:
输入一段英文,根据段落中的英文字符,及常见标点,空格以及换行符对段落进行分割
统计英文单词在段落中出现的次数并输出单词以及其出现的次数,并对结果进行排序。
代码分析:
1、输入一段英文;
2、用StringTokenizer将字符串分解;
3、将分解的结果进行循环遍历,利用hashmap 不允许重复性,统计单词个数,如果单词重复出现则数量加1,否则map中添加新单词,并且数量设置为1;
4、调用sort()方法,实现Comparator.compare接口 ,对map进行排序,
5、循环遍历集合中的键值对,并输出;
1 执行代码 2 package zuoye1; 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.Comparator; 6 import java.util.HashMap; 7 import java.util.List; 8 import java.util.Map; 9 import java.util.StringTokenizer; 10 import java.util.Map.Entry; 11 //词频统计(统计每个单词出现的次数,输出单词并排序) 12 public class Word { 13 public static void main(String[] args) { 14 String sentence = " While sharing a nickel or a quarter may go a long way for them, it is hard to believe the people would simply lie over and die. But to some people in such an unfortunate situation, it is more than simple surrender but another aspect of personal proportions that have led them to lose hope and live the rest of their days in misery."; //将要输入的句子或段落。 15 int wordCount=0; //每个单词出现的次数。 16 HashMap<String,Integer> map=new HashMap<String,Integer>();//用于统计各个单词的个数,排序 17 StringTokenizer token=new StringTokenizer(sentence);//这个类会将字符串分解成一个个的标记 18 while(token.hasMoreTokens()){ //循环遍历 19 wordCount++; 20 String word=token.nextToken(", ?.!:\"\"''\n"); //括号里的字符的含义是说按照,空格 ? . : "" '' \n去分割 21 if(map.containsKey(word)){ //HashMap不允许重复的key,所以利用这个特性,去统计单词的个数 22 int count=map.get(word); 23 map.put(word, count+1); //如果HashMap已有这个单词,则设置它的数量加1 24 }else 25 map.put(word, 1); //如果没有这个单词,则新填入,数量为1 26 } 27 System.out.println("总共单词数:"+wordCount); 28 sort(map); //调用排序的方法,排序并输出! 29 } 30 //排序 31 public static void sort(HashMap<String,Integer> map){ 32 //声明集合folder,存放map键值对 33 List<Map.Entry<String, Integer>> folder = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); 34 Collections.sort(folder, new Comparator<Map.Entry<String, Integer>>() { 35 public int compare(Map.Entry<String, Integer> obj1, Map.Entry<String, Integer> obj2) { 36 return (obj2.getValue() - obj1.getValue()); 37 } 38 }); 39 //输出 40 for (int i = 0; i < folder.size(); i++) { 41 Entry<String, Integer> en = folder.get(i); 42 System.out.println(en.getKey()+":"+en.getValue()); 43 } 44 } 45 }
执行结果
1 总共单词数:64 2 to:3 3 a:3 4 people:2 5 of:2 6 and:2 7 them:2 8 is:2 9 it:2 10 the:2 11 in:2 12 but:1 13 for:1 14 surrender:1 15 long:1 16 unfortunate:1 17 over:1 18 more:1 19 would:1 20 While:1 21 But:1 22 misery:1 23 live:1 24 such:1 25 or:1 26 that:1 27 aspect:1 28 simply:1 29 than:1 30 rest:1 31 some:1 32 quarter:1 33 go:1 34 hope:1 35 have:1 36 simple:1 37 way:1 38 believe:1 39 another:1 40 personal:1 41 sharing:1 42 die:1 43 hard:1 44 situation:1 45 may:1 46 lose:1 47 proportions:1 48 days:1 49 led:1 50 an:1 51 nickel:1 52 their:1 53 lie:1
coding.net 地址 : https://coding.net/u/linliaimeli/p/Word.java/git