http://www.cnblogs.com/120626fj/p/7533435.html
阿新 • • 發佈:2017-09-19
read char log 文件 nbsp btn 進行 nod 比較
1.打開文件
1 FILE *fp; //文件指針 2 fp = fopen("D:\\test.txt", "r"); //只讀方式打開文件 3 if (fp == NULL) 4 { 5 printf("文件打開失敗"); 6 exit(0)
2.讀取文本
1 char buf[1000] = { 0 }; //buffer預清空,否則結尾有出亂碼的可能 2 fread(buf, sizeof(buf), 1, fp); 3printf("%s\n", buf);
3.結構體定義
1 typedef struct BinaryTree { 2 char str; //單詞 3 int count; //出現次數 4 struct BinaryTree * lchild; 5 struct BinaryTree * rchild; 6 }BTNode;
4.給BTNode分配內存
1 BTNode* talloc(void) 2 {3 return (BTNode*)malloc(sizeof(BTNode)); 4 }
5.比較兩個字符串(單詞)大小
1 int strcmp(char *s1, char *s2) 2 { 3 int i; 4 for (i = 0; s1[i] == s2[i]; i++) //相等返回0 5 if (s1[i] == ‘\0‘) 6 return 0; 7 if (s1[i] - s2[i] != 0) //不相等返回18 return 1; 9 }
5.構建單詞二叉樹
1 void insert(BTNode ** tree, char * count) { 2 BTNode * temp = NULL; 3 if (!(*tree)) { 4 temp = (BTNode*)malloc(sizeof(BTNode)); 5 temp->lchild = temp->rchild = NULL; 6 temp->count = 1; 7 *tree = temp; 8 return; 9 } 10 11 if (cmp(count, (char *)(*tree)->str)) { 12 insert(&(*tree)->lchild, count); 13 } 14 else if (cmp(count, (char *)(*tree)->str)) { 15 insert(&(*tree)->rchild, count); 16 } 17 else { 18 (*tree)->count++; 19 } 20 }
總結
對於統計單詞出現的次數,我的想法是把文本內容看成一個個字符串,通過讀取字符串,建立一個二叉樹,建立二叉樹的過程就是在進行單詞頻率統計工作,最後遍歷一次二叉樹就可以得到文本出現的所有單詞,把單詞和詞頻放入二維數組中。但是我的代碼最終沒能運行成功,沒有實現作業要求的功能。
git: https://coding.net/u/a284617374/p/123/git/blob/master/fail.cpp
要改進
http://www.cnblogs.com/120626fj/p/7533435.html