#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
struct node排序
{
bool operator()(const string &a,const string &b)
{
if(a.compare(b)<0)
{
return 1;
}
else
{
return 0;
}
}
};
int main()
{
string str1;
unsigned char c;//要包含中文,所以是定义成无符号整型.
char Read_txt[50];
FILE *out;
int ok=1;
int h=0;
map<string,int,node> ma;
map<string,int,node>::iterator j;
long long int end,start;
cout<<"输入测试文件 ";
scanf("%s",Read_txt);
str1.clear();
out=fopen(Read_txt,"r");
fseek(out,0,SEEK_END); //out移动到文件的结尾,并不是最后一个字符而是文件的结束标记
//fread((char*)&c,sizeof(char),1,out);
//printf("%c\n",c);
end=ftell(out);//距离文件开头所偏移的字节数,(取值可以是0,1,2,3.......)即所有的字节数 。 因此end刚好等于文件的字节数
fseek(out,0,SEEK_SET);
start=ftell(out);//距离文件开头所偏移的字节数,是0,即是第一个字符。
//printf("%d %d\n",end,start);
if(out==NULL)
{
cout<<"文件打开失败!"<<endl;
}
else
{
str1.clear();
//fread((char*)&c,sizeof(char),1,out);
while(start!=end)//c=getchar(),c!='\n'//!feof(out)//只有当文件位置指针(fp->_ptr)到了文件末尾,然后再发生读/写操作时,标志位(fp->_flag)才会被置为含有_IOEOF。然后再调用feof(),才会得到文件结束的信息。
{
fread((unsigned char*)&c,sizeof(unsigned char),1,out);
if((c>='A'&&c<='Z')||(c>='a'&&c<='z')||(c=='-')||(c>='0'&&c<='9')||(c==39))当是word的时候,包括由阿拉伯数字
{
//ok=1;
if(c>='A'&&c<='Z')///用来统计字母个数
{
c=c-'A'+'a';
}
str1.push_back(c);
}
else if(c>127)///当是汉字的时候(包括汉字的标点符号)
{
unsigned char b;
if(str1.size()==1)
{
b=str1[0];
if(b>127)
{
h=1;///当是汉字时
str1.push_back(c);
}
}//其他的说明不是汉字
ok=2;
}
else
{
ok=0;
}
if((ok==0)||(ok==2))
{
if(!str1.empty()&&h==0)//当str1不是汉字的时候
{
if((j=ma.find(str1))!=ma.end())
{
ma[str1]++;
}
else
{
ma.insert(make_pair(str1,1));
}
str1.clear();
if(ok==2)//当c是汉字的一部分的时候
{
str1.push_back(c);
}
}
else if(!str1.empty()&&h==1)//当是汉字的时候 (包括中文标点符号)
{
if((j=ma.find(str1))!=ma.end())
{
ma[str1]++;
}
else
{
ma.insert(make_pair(str1,1));
}
str1.clear();
h=0;
}
else
{
if(c>127)//当只是汉字的一部分时
{
str1.push_back(c);
}
//其他的情况是当连续的空格时.
}
ok=1;
}
start=ftell(out);
}
if(!str1.empty())/统计最后一个单词,当最后一个单词形式如单词+标点符号的形式时,str1的值为空,此时不需要进行下一步了。
{
if((j=ma.find(str1))!=ma.end())
{
ma[str1]++;
}
else
{
ma.insert(make_pair(str1,1));
}
}
if(ma.empty())
{
cout<<"无单词"<<endl;
}
else
{
for(j=ma.begin();j!=ma.end();++j)//输出单词及频度
{
cout<<j->first<<' '<<j->second<<endl;
}
}
}
return 0;
}
统计文中每个单词(包括中文)出现的次数
最新推荐文章于 2021-12-26 23:05:45 发布