詞頻統計是文本處理中的基礎功能,廣泛應用於搜索引擎、自然語言處理、數據分析等領域。本文提供一個完整的 Java 實現方案,包含文本預處理、詞頻計數、結果排序等核心步驟。
package com.gpdi.action;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WordsStatistics {
// 內部類:用於封裝計數器
private static class Counter {
int count;
Counter(int count) { this.count = count; }
}
// 統計結果封裝類
public static class WordCount {
private String word;
private int count;
public WordCount(String word, int count) {
this.word = word;
this.count = count;
}
public String getWord() { return word; }
public int getCount() { return count; }
}
/**
* 詞頻統計主方法
* @param text 待統計文本
* @return 按詞頻降序排列的單詞列表
*/
public List<WordCount> statistics(String text) {
List<WordCount> result = new ArrayList<>();
if (text == null || text.trim().isEmpty()) {
return result;
}
// 文本預處理:轉小寫、移除標點符號
String processed = text.toLowerCase()
.replaceAll("'s", "")
.replaceAll("[,.\\-:!\\n]", "");
// 分詞並統計
String[] words = processed.split("\\s+");
Map<String, Counter> frequencyMap = new HashMap<>();
for (String word : words) {
word = word.trim();
if (!word.isEmpty()) {
Counter counter = frequencyMap.get(word);
if (counter != null) {
counter.count++;
} else {
frequencyMap.put(word, new Counter(1));
}
}
}
// 轉換為結果列表
for (Map.Entry<String, Counter> entry : frequencyMap.entrySet()) {
result.add(new WordCount(entry.getKey(), entry.getValue().count));
}
// 排序:先按詞頻降序,再按字母序升序
Collections.sort(result, (o1, o2) -> {
if (o1.getCount() != o2.getCount()) {
return o2.getCount() - o1.getCount(); // 詞頻降序
}
return o1.getWord().compareToIgnoreCase(o2.getWord()); // 字母序升序
});
return result;
}
// 測試主方法
public static void main(String[] args) {
String text = "Pinterest is might be aa ab aa ab marketer's dream - ths site is largely used to curate products";
WordsStatistics analyzer = new WordsStatistics();
List<WordCount> result = analyzer.statistics(text);
for (WordCount wc : result) {
System.out.println(wc.getWord() + "*" + wc.getCount());
}
}
}
\\s+ 按空白字符分割單詞[,.\\-:!\\n]實際項目中可根據需求擴展:
該實現邏輯清晰、擴展性強,可直接應用於文本分析、關鍵詞提取等業務場景。