h0945466 发表于 2017-7-3 16:10:33

【第一周】c++实现词频统计

  coding.net地址:https://coding.net/u/Boxer_
  ssh:git@git.coding.net:Boxer_/homework.git
  --------------------------------------------------------------------------------------
  9.6更新了一下,按老师要求把程序分块发表了,git版本控制内容比较多,正在学(2016.9.9已学)。
  --------------------------------------------------------------------------------------
  需求:从一个英文txt中读取内容,实现词频统计。
  现完成:基本功能大概完成了,由于编程基础比较差,文件操作部分还不是很熟练,我发现从文件中提取字符串流读取到程序的string对象中,会把所有的空格过滤掉,导致没法统计单词频率,目前还没找到解决方法,只能先手动输入文章了。ORZ...
  好好学习java,目前看来,处理字符串等问题还是java有成熟的解决方案。
  1.建立一个word类,包含str和count两个属性,分别代表word的内容和个数。包含一个exchange方法,用来交换两个word的内容。



class Word
{
public:
Word() : Str(""), Count(0)
{}
string Str;
int Count;
void exchange(Word &word)
{
string tStr = word.Str;
int tCount = word.Count;
word.Str = Str;
word.Count = Count;
Str = tStr;
Count = tCount;
}
};
  2.用来统计单词的个数。



void CalcCount(Word * words, string &newWord, int size)
{
int i = 0;
for(; i < size; i++)
{
if(words.Str == newWord)
{
words.Count++;
return;
}
else if(words.Str == "")
break;
}
words.Str = newWord;
words.Count = 1;
}
  3.用来进行单词排序,采用冒泡算法。



void SortWordDown(Word * words, int size)
{
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size-1; j++)
{
if(words.Count <words.Count)
{
words.exchange(words);
}
}
}
}
  4.主函数



int main()
{
Word * words;
string content;
cout << "输入一段英文:";
getline(cin, content);
//计算单词总数
int wCount = 1;
for(unsigned int i = 0; i < content.length(); i++)
{
if(content == ' ')
wCount++;
}
words = new Word;
string::size_type offset = content.find(' ');//单词都是以空格隔开
while(offset != string::npos)
{
string wStr = content.substr(0, offset);
content.erase(0, offset+1);
CalcCount(words, wStr, wCount);
offset = content.find(' ');
}
CalcCount(words, content, wCount);//计算最后一个单词

SortWordDown(words, wCount);
int printCount = wCount ;
for(int i = 0; i < printCount; i++)
{
cout << words.Str << "\t" << words.Count <<endl;
}
delete [] words;
return 0;
}
页: [1]
查看完整版本: 【第一周】c++实现词频统计