首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 字符串詞頻統計實現:完整代碼與算法解析

     編輯:Java 程式設計入門

Java 實現字符串詞頻統計

詞頻統計是文本處理中的基礎功能,廣泛應用於搜索引擎、自然語言處理、數據分析等領域。本文提供一個完整的 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());
        }
    }
}

算法流程解析

  1. 文本預處理:統一轉為小寫,移除擁有格、標點符號、換行符等干擾字符
  2. 分詞處理:使用正則表達式 \\s+ 按空白字符分割單詞
  3. 詞頻統計:採用 HashMap 以單詞為 Key,計數器為 Value 進行 O(1) 統計
  4. 結果排序:使用 Comparator 實現雙重排序邏輯(詞頻優先,字母序次之)

關鍵技術點

  • 內部類封裝計數器:避免 Integer 不可變導致的頻繁對象創建
  • 正則表達式優化:合併多個 replaceAll 為單一字符類 [,.\\-:!\\n]
  • Java 8 Lambda 表達式:簡化 Comparator 實現,提升代碼可讀性
  • 邊界條件處理:空值檢查、空白字符過濾、大小寫統一

擴展建議

實際項目中可根據需求擴展:

  • 引入停用詞過濾
  • 支援中文分詞(整合 Jieba、Ansj 等分詞庫)
  • 使用 Trie 樹優化大規模文本統計性能
  • 輸出格式化為 JSON/CSV 便於後續分析

該實現邏輯清晰、擴展性強,可直接應用於文本分析、關鍵詞提取等業務場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved