import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class word2 {
public static void main(String[] args)throws IOException//扔掉很重要
{
File file = new File("HP7.txt");
txtString2(file);
}
/*
* 统计单词
*/
public static void txtString2(File file) throws IOException{
System.out.println("前N个常出现的单词");
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);//构造一个BufferedReader类来读取文件
StringBuffer sb = new StringBuffer();
String line =null;
while ((line=br.readLine())!=null){
sb.append(line);//将读取出的字符追加到stringbuffer中
}
fr.close();
// 关闭读入流
String str = sb.toString().toLowerCase(); // 将stringBuffer转为字符并转换为小写
String[] words = str.split("[^(a-zA-Z)]+"); // 非单词的字符来分割,得到所有单词
Map<String ,Integer> map = new HashMap<String, Integer>() ;
for(String word :words){
if(map.get(word)==null){ // 若不存在说明是第一次,则加入到map,出现次数为1
map.put(word,1);
}else{
map.put(word,map.get(word)+1); // 若存在,次数累加1
}
}
// 排序
List<Map.Entry<String ,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
Comparator<Map.Entry<String,Integer>> comparator = new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> left, Map.Entry<String, Integer> right) {
int i=left.getValue()-right.getValue();
if(i==0) {
return (right.getKey().compareTo(left.getKey()));
}
return (left.getValue().compareTo(right.getValue()));
}
};
// 集合默认升序
Collections.sort(list,comparator);
for(int i=0;i<n;i++){// 由高到低输出
System.out.print(list.get(list.size()-i-1).getKey() +":"+list.get(list.size()-i-1).getValue()+" ");
}
}
}