文章获取与单词统计排序

来源:互联网 发布:李谷一 知乎 编辑:程序博客网 时间:2024/06/05 16:52
/****************** Exercise 21 ****************** Using a Map<String,Integer>, follow the form of* UniqueWords.java to create a program that counts* the occurrence of words in a file. Sort the* results using Collections.sort() with a second* argument of String.CASE_INSENSITIVE_ORDER (to* produce an alphabetic sort), and display the result.***********************************************/import java.util.*;import net.mindview.util.*;public class E21_WordsNumber {public static void main(String[] args){//countFileWord("E21_WordsNumber.java");}public static void countFileWord(String fileName){//m1插入String.CASE_INSENSITIVE_ORDER,非题中要求Map<String, Integer> m1 = new TreeMap<String, Integer> (String.CASE_INSENSITIVE_ORDER);List<String> words1 = new TextFile(fileName, "\\W+");for(String word: words1)countWord(m1, word);System.out.println("the number of every word is: " + m1);//按题要求如下:Map<String, Integer> m2 = new TreeMap<String, Integer> ();List<String> words2 = new TextFile(fileName, "\\W+");for(String word: words2)countWord(m2, word);List<String> keys = new ArrayList<String>(m2.keySet());Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);for(String key: keys){System.out.print(key + ">=" + m2.get(key) + ". ");}System.out.println();}private static void countWord(Map<String, Integer> m, String s){Integer freq = m.get(s);m.put(s, freq == null? 1: freq+1);}}

原创粉丝点击