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

C++ 趣味程式設計:英文文章字母頻率統計與鄰近分析完整解法

     編輯:程式設計綜合問答

專案需求

下載超過 10,000 個字母的英文文章(`data.txt`),完成四項任務並輸出至 `result.txt`:

  1. 統計 26 個字母出現頻率(百分比)並排序
  2. 輸入一字母,找出與其最鄰近出現的前三字母
  3. 找出最高頻率的前五個單字並排序
  4. 合理格式化輸出所有結果

核心演算法設計

1. 字母頻率統計

#include <fstream>
#include <map>
#include <vector>
#include <algorithm>
#include <cctype>

void analyzeFrequency(const string& filename) {
    ifstream fin(filename);
    map<char, int> freq;
    int total = 0;
    char ch;
    while (fin.get(ch)) {
        if (isalpha(ch)) {
            ch = tolower(ch);
            freq[ch]++;
            total++;
        }
    }
    // 轉 vector 排序
    vector<pair<char, double>> vec;
    for (auto& p : freq)
        vec.emplace_back(p.first, p.second * 100.0 / total);
    sort(vec.begin(), vec.end(),
         [](auto& a, auto& b) { return a.second > b.second; });
    // 輸出...
}

2. 鄰近字母分析(Bigram 統計)

// 建立 26x26 矩陣
int adj[26][26] = {0};
string text; // 讀取全文小寫字母
for (size_t i = 0; i + 1 < text.size(); ++i) {
    int a = text[i] - 'a';
    int b = text[i+1] - 'a';
    if (a>=0 && a<26 && b>=0 && b<26)
        adj[a][b]++, adj[b][a]++; // 雙向計數
}

// 查詢目標字母 top 3
vector<pair<char, int>> neighbors;
for (int j = 0; j < 26; ++j)
    if (adj[target][j] > 0)
        neighbors.emplace_back('a'+j, adj[target][j]);
sort(neighbors.begin(), neighbors.end(),
     [](auto& a, auto& b) { return a.second > b.second; });
// 取前三...

3. 單字頻率統計

map<string, int> wordFreq;
string word;
while (fin >> word) {
    // 移除標點、轉小寫
    string clean;
    for (char c : word) if (isalpha(c)) clean += tolower(c);
    if (!clean.empty()) wordFreq[clean]++;
}
// 排序輸出前五...

完整程式架構建議

int main() {
    // 1. 讀取 data.txt 到 string fullText
    // 2. 呼叫三個分析函式,收集結果
    // 3. 寫入 result.txt
    ofstream fout("result.txt");
    fout << "=== 字母頻率 ===\n";
    // ...
    fout << "\n=== 鄰近分析 ===\n";
    // ...
    fout << "\n=== 高頻單字 ===\n";
    // ...
    return 0;
}

效能優化提示

  • 使用 `array` 替代 `map` 加速字母計數
  • 單字統計可用 `unordered_map` O(1) 平均查找
  • 大檔案建議分塊讀取,避免記憶體壓力
  • 鄰近矩陣固定 26x26,堆疊配置極快

常見陷阱

  1. 忘記處理大小寫統一
  2. 單字分割未移除標點符號(如 `word,` vs `word`)
  3. 鄰近統計未考慮雙向性(A-B 與 B-A)
  4. 輸出格式不符合題目要求的「合理形式」
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved