首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 統計英文文本單詞總數與不重複單詞數:正則清洗 + Split + Map 計數

     編輯:程式設計疑難解答

題目需求

輸入一段英文文本,統計:1) 單詞總數 2) 不重複單詞數。例:「I am a good student. I am in Zhengzhou.」→ 9 個單詞,7 個不重複。

解決步驟

  1. 去標點:用正則 `replaceAll("[.|;|\\?]", " ")` 將標點替換為空格(避免單詞粘連)。
  2. 分割:`split(" ")` 按空格分割,得到單詞陣列。
  3. 計數:用 `Map` 以單詞為 Key、出現次數為 Value 累加。

完整代碼

import java.util.*;

public class WordCounter {
    public static String clean(String input) {
        if (input == null) return null;
        return input.replaceAll("[.|;|\\?]", " "); // 可擴展更多標點
    }

    public static Map count(String input) {
        Map map = new HashMap<>();
        if (input == null || input.isEmpty()) return map;
        String[] words = input.split(" ");
        for (String w : words) {
            if (w.isEmpty()) continue; // 過濾多空格產生的空串
            map.put(w, map.getOrDefault(w, 0) + 1);
        }
        return map;
    }

    public static void main(String[] args) {
        String text = "I am a good student.I am in Zhengzhou.Ha?";
        String cleaned = clean(text);
        System.out.println("清洗後: " + cleaned);
        Map result = count(cleaned);
        System.out.println("總單詞數: " + result.values().stream().mapToInt(Integer::intValue).sum());
        System.out.println("不重複單詞數: " + result.size());
        System.out.println("明細: " + result);
    }
}

輸出範例

清洗後: I am a good student I am in Zhengzhou Ha 
總單詞數: 9
不重複單詞數: 7
明細: {Zhengzhou=1, Ha=1, I=2, am=2, a=1, good=1, student=1, in=1}

進階優化

  • 正則合併:`replaceAll("[\\p{Punct}]", " ")` 一次性替換所有標點。
  • 大小寫敏感:題目未說明,通常視為敏感;若不敏感,`w.toLowerCase()` 後再 put。
  • 大文本:用 `Scanner` 逐 token 讀取,避免一次性載入巨大字串。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved