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

C++ 單詞統計:基於 set 與 map 的詞頻統計實現

     編輯:關於C語言

需求

讀取文本文件 a.txt,按標點(, .)分詞,統計:

  1. 所有不重複單詞集合(set)。
  2. 每個單詞出現次數(map)。

類設計

CWord

封裝單詞字符串,重載 operator<(供 set 排序)與 operator==(供 map 查找)。

CWordSet

內含 set<CWord>,提供 AddString 與 show。

CWordMap

內含 map<CWord, int>,AddString 實現詞頻遞增,Show 輸出「單詞\t次數」。

主流程

[cpp]
int main() {
    CWordSet wordSet; CWordMap wordMap;
    ifstream in("a.txt");
    string s, delimset = ",.";
    while (getline(in, s)) {
        if (s.empty()) continue;
        // 替換標點為空格
        for (size_t pos = 0; (pos = s.find_first_of(delimset, pos)) != string::npos; )
            s.replace(pos, 1, " ");
        istringstream iss(s);
        while (iss >> s) {
            if (!s.empty()) { wordSet.AddString(s); wordMap.AddString(s); }
        }
    }
    wordSet.show(cout); cout << endl;
    wordMap.Show(cout);
}

關鍵點

  • set 自動去重且有序;map 鍵值對統計頻次。
  • 使用 istringstream 配合 operator>> 自動按空白分詞。
  • CWord 的比較運算符確保容器正常工作。

擴展建議

  • 轉小寫實現不區分大小寫統計。
  • 過濾停用詞。
  • 大文件可用 unordered_map + 自定義哈希提升性能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved