码迷,mamicode.com
首页 > 其他好文 > 详细

词频统计_输入到文件

时间:2016-06-26 18:26:34      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

   /*337.in.txt: 
*To being or not to being , is a question .
*Do you have a question .
*Yes , I have a question . I like apple , apple a very declicious !
***/
/*337.out.txt:
*所有单词为:    单词数为:
   Do              1
   I               2
   To              1
   Yes             1
   a               4
   apple           2
   being           2
   declicious      1
   have            2
   is              1
   like            1
   not             1
   or              1
   question        3
   to              1
   very            1
   you             1
   ***/
1 #include <iostream> 2 #include <cctype> 3 #include <fstream> 4 #include <cstring> 5 using namespace std; 6 7 const int maxList = 1010 + 10; //单词表的最大值 8 const int maxWord = 100 + 10; //单词长度的最大值 9 10 struct WordList 11 { 12 char word[maxWord]; //单词 13 int fre; //词频 14 }; 15 16 void Sort(WordList list[], int length) //将单词表排序 17 { 18 int i, j, k; 19 for (i = 0; i < length-1; i++) 20 { 21 k = i; 22 for (j = k+1; j < length; j++) 23 { 24 if (strcmp(list[k].word, list[j].word) > 0) 25 k = j; 26 } 27 if (k != i) { 28 WordList tmp = list[i]; 29 list[i] = list[k]; 30 list[k] = tmp; 31 } 32 } 33 } 34 35 //因为单词长度不同,所以此函数用来规范输出格式 36 void ShowOrder(WordList w, char extra, int len, ofstream& out) 37 { 38 out << w.word; 39 for (int i = 1; i <= 16-len; i++) 40 { 41 out << extra; 42 } 43 out << w.fre << endl; 44 } 45 46 int main() 47 { 48 ifstream in("337.in.txt"); //读取单词文件 49 ofstream out("337.out.txt"); //写入单词及其个数文件 50 51 if (!in) { 52 cout << "failure !" << endl; return 1; 53 } 54 55 WordList list[maxList]; //单词表 56 int N = 0; //单词的数量 57 char tmp[maxWord]; //读取单词 58 59 while (in >> tmp) 60 { 61 int i; 62 for (i = 0; i < N; i++) //在单词表中查找该单词 63 { 64 if (strcmp(list[i].word, tmp) == 0) { //找到则,fre++; 65 list[i].fre++; break; 66 } 67 } 68 if (i == N && isalpha(tmp[0])) //找不到则添加该单词,且该词频置为1,单词表数目N++ 69 { //标点符号不统计 70 strcpy(list[N].word, tmp); 71 list[N++].fre = 1; 72 } 73 } 74 75 Sort(list, N); //可以将单词表排序后写入文件 76 out << "所有单词为:\t单词数为: \n"; 77 for (int i = 0; i < N; i++) 78 { 79 ShowOrder(list[i], , strlen(list[i].word), out); 80 } 81 return 0; 82 }

 

词频统计_输入到文件

标签:

原文地址:http://www.cnblogs.com/douzujun/p/5618219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!