要在Java中分析文本的高频次数据,你可以使用HashMap来记录每个单词的出现次数。以下是一个简单的示例代码,演示如何读取文本文件,统计每个单词的频率,并输出出现次数最多的单词。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author weimeilayer@gmail.com ✨
* @date 💓💕 2024年10月17日 🐬🐇 💓💕
*/
public class WordFrequencyAnalyzer {
public static void main(String[] args) {
String filePath = "d://textfile.txt"; // 替换为你的文本文件路径
Map<String, Integer> wordCountMap = new HashMap<>();
// 读取文本文件并统计单词频率
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
// 使用正则表达式分割单词,并将其转换为小写
String[] words = line.toLowerCase().split("\\W+");
for (String word : words) {
if (!word.isEmpty()) {
wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
// 排序并输出高频次单词
int topN = 10; // 设置要输出的高频单词数量
List<Map.Entry<String, Integer>> sortedEntries = wordCountMap.entrySet()
.stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(topN)
.collect(Collectors.toList());
System.out.println("Top " + topN + " Word Frequencies:");
sortedEntries.forEach(entry -> {
System.out.println(entry.getKey() + ": " + entry.getValue());
});
}
}
输出所有
// 输出高频次单词
System.out.println("Word Frequencies:");
wordCountMap.forEach((word, count) -> {
System.out.println(word + ": " + count);
});
python 案例
from collections import Counter
import re
def analyze_word_frequency(file_path, top_n=10):
# 读取文本文件并统计单词频率
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read().lower() # 将文本转换为小写
# 使用正则表达式分割单词
words = re.findall(r'\b\w+\b', text)
# 统计单词频率
word_count = Counter(words)
# 输出高频次单词
print(f"Top {top_n} Word Frequencies:")
for word, count in word_count.most_common(top_n):
print(f"{word}: {count}")
# 示例用法
file_path = 'd://textfile.txt' # 替换为你的文本文件路径
analyze_word_frequency(file_path, top_n=10)
4669

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



