package test;
import java.io.*;
import java.util.*;
public class wordCount2 {
public static void main(String[] args) throws IOException {
File file = new File("/Users/jiachenglin/Desktop/HP7.txt");
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "gbk");
BufferedReader br = new BufferedReader(isr)) {
String str;
Map<String, Integer> map = new TreeMap<>();
while ((str = br.readLine()) != null) {
String[] words = str.split("[ ,.:;'!…\"{}()?\\[\\]]");
for (int i = 0; i < words.length; i++) {
String key = words[i].toLowerCase().trim();
//添加单词
if (key.length() > 0 && Character.isLetter(key.charAt(0))) {
if (!map.containsKey(key))
map.put(key, 1);
else
map.put(key, map.get(key) + 1);
}
}
}
//Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
List<Map.Entry<String, Integer>> entrys = new ArrayList<>(map.entrySet());
Collections.sort(entrys, new myComparator());
int flag=0;
String[] a=new String[1000000];
System.out.println("请输入要查看的单词数");
Scanner s=new Scanner(System.in);
flag=s.nextInt();
int i=0;
for (Map.Entry<String, Integer> entry : entrys) {
//输出单词和数目
a[i]=entry.getKey()+" "+entry.getValue();//利用字符串数组将Map中的key与value组合
i++;
}
for(int j=0;j<flag;j++){
System.out.println(a[j]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class myComparator implements Comparator<Map.Entry> {
public int compare(Map.Entry o1, Map.Entry o2) {
return ((Integer) o2.getValue()).compareTo((Integer) o1.getValue());
}
}