下載超過 10,000 個字母的英文文章(`data.txt`),完成四項任務並輸出至 `result.txt`:
#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; });
// 輸出...
}
// 建立 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; });
// 取前三...
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;
}