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 首次发布
该程序读取指定文件(C:
ohup.out),统计其中汉字的出现次数,并按频率降序输出前10个最常见的汉字。程序使用HashMap存储每个汉字及其出现次数,通过PriorityQueue实现频率排序。
1587

被折叠的 条评论
为什么被折叠?



