(1). 实现一个控制台程序,给定一段英文字符串,统计其中各个英文单词(4字符以上含4字符)的出现频率。 附加要求:读入一段文本文件,统计该文本文件中单词的频率。
(2). 性能分析:
本次作业难度对我来说较大,百度和java的书都看了很久,花了很长时间,并且最后在同学的帮助下,才顺利的完成了这次作业。
原本预计用时 半天,实际用时 超过一天。
package a; import java.util.Map; import java.util.StringTokenizer; import java.util.Map.Entry; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class a1 { public static void main(String arg[]){ String sentence="Word is case insensitive, i.e. “file”, “FILE” and “File” are considered the same word."; Map<String,Integer> map=new HashMap<String,Integer>(); String turn_sentence= sentence.toLowerCase(); StringTokenizer token=new StringTokenizer(turn_sentence); while(token.hasMoreTokens()){ String word=token.nextToken(", :\"\".“”"); if(map.containsKey(word)){ int count=map.get(word); map.put(word, count+1); } else map.put(word, 1); } sort(map); } public static void sort(Map<String,Integer> map) { List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); for (int i = 0; i < infoIds.size(); i++) { Entry<String, Integer> id = infoIds.get(i); if(id.getKey().length()>=4) {System.out.println(id.getKey()+":"+id.getValue()); } } } }
测试结果

原文:http://www.cnblogs.com/chenxin123/p/5283890.html