标签:
需求:从一个英文txt中读取内容,实现词频统计。
现完成:基本功能大概完成了,由于编程基础比较差,文件操作部分还不是很熟练,我发现从文件中提取字符串流读取到程序的string对象中,会把所有的空格过滤掉,导致没法统计单词频率,目前还没找到解决方法,只能先手动输入文章了。ORZ...
好好学习java,目前看来,处理字符串等问题还是java有成熟的解决方案。
1 /** 2 * 对一段英文的词频统计 3 4 */ 5 #include <iostream> 6 #include <string> 7 8 using namespace std; 9 /** 10 * 单词对象 11 */ 12 struct Word 13 { 14 Word() : Str(""), Count(0) 15 {} 16 string Str; 17 int Count; 18 19 /** 20 * 交换单词(用于排序) 21 * word 交换的单词对象 22 */ 23 void exchange(Word &word) 24 { 25 string tStr = word.Str; 26 int tCount = word.Count; 27 word.Str = Str; 28 word.Count = Count; 29 Str = tStr; 30 Count = tCount; 31 } 32 }; 33 34 /** 35 * 统计词频 36 * words 单词数组 37 * newWord 单词内容 38 * size 单词总数 39 */ 40 void CalcCount(Word * words, string &newWord, int size) 41 { 42 int i = 0; 43 for(; i < size; i++) 44 { 45 if(words[i].Str == newWord) 46 { 47 words[i].Count++; 48 return; 49 } 50 else if(words[i].Str == "") 51 break; 52 } 53 words[i].Str = newWord; 54 words[i].Count = 1; 55 } 56 57 58 void SortWordDown(Word * words, int size) 59 { 60 for(int i = 0; i < size; i++) 61 { 62 for(int j = 0; j < size-1; j++) 63 { 64 if(words[j].Count < words[j+1].Count) 65 { 66 words[j].exchange(words[j+1]); 67 } 68 } 69 } 70 } 71 72 int main() 73 { 74 Word * words; 75 string content; 76 cout << "输入一段英文:"; 77 getline(cin, content); 78 79 //计算单词总数 80 int wCount = 1; 81 for(unsigned int i = 0; i < content.length(); i++) 82 { 83 if(content[i] == ‘ ‘) 84 wCount++; 85 } 86 words = new Word[wCount]; 87 88 string::size_type offset = content.find(‘ ‘);//单词都是以空格隔开 89 while(offset != string::npos) 90 { 91 string wStr = content.substr(0, offset); 92 content.erase(0, offset+1); 93 CalcCount(words, wStr, wCount); 94 offset = content.find(‘ ‘); 95 } 96 CalcCount(words, content, wCount);//计算最后一个单词 97 98 SortWordDown(words, wCount); 99 int printCount = wCount ; 100 101 for(int i = 0; i < printCount; i++) 102 { 103 cout << words[i].Str << "\t" << words[i].Count << endl; 104 } 105 106 delete [] words; 107 return 0; 108 }
标签:
原文地址:http://www.cnblogs.com/Boxer1994/p/5840812.html