標籤:upper 技術分享 color image log show let private tor
問題
對指定檔案中的英文字元進行頻率的統計,不區分大小寫(都按照大寫統計),忽略非字母。並使用頻率長條圖的形式顯示出來。
來源
貼吧吧友提問
代碼
#include<iostream>#include<cctype>#include<cstdio>#include<cassert>using namespace std;class LetterCount { private: enum{LETTERS_SUM=26}; //常量:個英文字母有26個 string file_path; //檔案路徑 int total_letters; //統計到的字母的總個數 int letter_count[LETTERS_SUM]; //儲存每個單詞的出現次數 double letter_frequence[LETTERS_SUM]; //儲存每個單詞的出現頻率 //不允許使用 LetterCount(const LetterCount& le); //複製函數 LetterCount& operator=(const LetterCount& le); //賦值函數 public: void setFilePath(const char *path){file_path = path;} //設定檔案的路徑 inline function void analyse(); //統計函數 void showGraph() const; //列印統計圖 LetterCount(); LetterCount(const char *path); ~LetterCount(); }; LetterCount::LetterCount():file_path(),total_letters(0){ for(int i=0;i<LETTERS_SUM;++i) { letter_count[i] = 0; letter_frequence[i] = 0.0; } }LetterCount::LetterCount(const char*path):file_path(path),total_letters(0){ for(int i=0;i<LETTERS_SUM;++i) { letter_count[i] = 0; letter_frequence[i] = 0.0; } }LetterCount::~LetterCount(){ // do nothing}void LetterCount::analyse(){ FILE*fp = fopen(file_path.c_str(),"r"); //開啟檔案 assert(fp!=NULL); char ch; while((ch=fgetc(fp))!=EOF) { if(isalpha(ch)) //如果不是英文字母,則忽略 { //忽略大小寫,全部安大寫統計 letter_count[ toupper(ch) -‘A‘]++; total_letters++; } } fclose(fp); //關閉檔案 //計算單詞的頻率 for(int i=0;i<LETTERS_SUM;++i) { letter_frequence[i] = (letter_count[i]*1.0)/total_letters ; } } void LetterCount::showGraph() const{ /* ***************樣圖 100| * | * * | * * * 0 |----------- A B C ... *********************/ for(int r=100;r!=0;--r) //統計圖有100行,代表百分百比 { if(r%10==0) //列印表的整數百分比,便於觀察. printf("%-3d",r); else printf(" "); printf("|"); for(char ch=‘A‘;ch<=‘Z‘;++ch) { if(int(((letter_frequence[ch-‘A‘]*100) +0.5)) >=r ) { printf(" *"); } else { printf(" "); } printf(" "); } printf("\n"); } printf("%-3d",0); for(char ch=‘A‘;ch<=‘Z‘;++ch) { printf("----"); } printf("\n");printf("%-3c",‘ ‘); for(char ch=‘A‘;ch<=‘Z‘;++ch) { printf(" %c",ch); } printf("\n");}int main(){ LetterCount lc("G:\\data.txt"); lc.analyse(); lc.showGraph(); return 0;}
效果
英文字元進行頻率的統計,長條圖輸出