import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
public class QueryTopWordFromFile {
public static void main(String[] args) throws IOException {
int top = 10;
File file = new File("C:\\nohup.out");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
Map<String, Integer> wordsCountMap = new HashMap<>();
String line = null;
Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
int lines = 0;
while ((line = bufferedReader.readLine()) != null) {
lines++;
String[] split = line.split("");
for (String s : split) {
wordsCountMap.merge(s, 1, Integer::sum);
}
}
System.out.println("lines: " + lines);
System.out.println(wordsCountMap);
PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue));
for (Map.Entry<String, Integer> next : wordsCountMap.entrySet()) {
String word = next.getKey();
if (pattern.matcher(word).matches()) {
if (queue.size() < top) {
queue.add(next);
} else if (next.getValue() > queue.peek().getValue()) {
queue.poll();
queue.add(next);
}
}
}
System.out.println("==========");
System.out.println(queue);
}
}
统计文件中出现最频繁的前TOP个汉字(Java版)
于 2022-09-07 20:35:10 首次发布
关键词由CSDN通过智能技术生成