个人项目-词频统计(语言:C++)

时间:2023-03-08 22:34:10

词频统计 (个人项目)

要求

(1). 实现一个控制台程序,给定一段英文字符串,统计其中各个英文单词(4字符以上含4字符)的出现频率。 附加要求:读入一段文本文件,统计该文本文件中单词的频率。

(2). 性能分析:


开发语言:C++

各个模块时间(预估/实际)(本来预估3-4h可完成,但实际花了将近6-7h)

  预估时间 实际时间
词频统计 1.5h 1.5h
大小写转换 0.75h 1h
长度小于4的单词删除 0.75h 1.5h
多个分隔符区分 1h 2h

由于上一次老师提过代码的规范性,所以这一次的代码我特意注意了代码的书写规范。

下面是源代码

 #include <iostream>
#include <string>
using namespace std; struct Word /* 单词对象 */
{
Word() : Str( "" ), Count( )
{
}
string Str;
int Count;
}; void CalcCount( Word *words, string &content, int size ) /* 统计词频 */
{
int i; /* words单词 content内容 size个数 */
for ( i = ; i < size; i++ )
{
if ( words[i].Str == content )
{
words[i].Count++;
return;
}else if ( words[i].Str == "" )
break;
}
words[i].Str = content;
words[i].Count = ;
} int main()
{
char ch;
Word *words;
string content;
cout << "输入一段英文:";
getline( cin, content );
while ( cin.get( ch ) ) /* 把所有小写字母换成大写字母 */
{
ch = cin.get(); /* 此部分存疑,可能是输入问题,这一部分无法实现 */
if ( <= ch && ch <= )
{
char (ch) = char(ch - );
break;
}
} int wCount = ; /* 计算单词总数 */
if ( content.length() < ) /* 长度小于4的单词删除 */
{
wCount--;
content.erase( , offset + );
offset = content.find( ' ' );
continue;
}
for ( unsigned int i = ; i < content.length(); i++ )
{
if ( content[i] == ' ' || content[i] == '\t' || content[i] == '\n' || content[i] == '.' || content[i] == ',' )
wCount++; /* 分隔符分为' ','\t','\n',',','.'五种 */
}
words = new Word[wCount]; string::size_type offset = content.find( ' ' || '\t' || '\n' || '.' || ',' ); /* 单词以分隔符隔开 */
while ( offset != string::npos )
{
string wStr = content.substr( , offset );
content.erase( , offset + );
CalcCount( words, wStr, wCount );
offset = content.find( ' ' || '\t' || '\n' || '.' || ',' );
}
CalcCount( words, content, wCount ); for ( int j = ; j < wCount; j++ ) /* 最后输出结果 */
{
cout << words[j].Str << ":" << words[j].Count << endl;
}
delete[] words;
return();
}

运行结果(老师给的例子):

个人项目-词频统计(语言:C++)


我的分析

由上图可以看出,结果并不完全正确,我的代码里面,小写字母全部转换成大写字母那一块出了问题。我前前后后大概改了十几次,也翻阅了C++书,我觉得可能是输入读取出了问题,但是怎么改都无济于事,这个问题算是存疑,之后我会借助同学或者老师的力量解决这个问题的。

我的总结

由于JAVA的初步学习我觉得还不够让我写出这样一个程序,所以我还是选择了C++语言写了这个程序。这次源代码,我花的时间比预计的时间多了很多,一部分原因是C++知识的疏漏和遗忘,另一部分原因就是题目的要求细节的难度比较高。这个词频统计的题目,虽然以前做过字母的统计,大小写转换,分隔符区分等等程序,但是要写出这个充满细节需要的程序,确实难上加难,甚至我最后还存了疑,在小写字母全部转换成大小字母这儿问题上,并没有完全解决,短时间内可能再卡在这里,所以我选择之后借助一个同学和老师的力量解决。

github链接https://github.com/liuyutianlyt/CalcCount.md