用C语言编程实现统计D:\file.txt文件每个英文单词出现的频次,并按英文单词出现频次升序顺序
用C语言编程实现统计D:\file.txt文件每个英文单词出现的频次,并按英文单词出现频次升序顺序将单词信息和频次信息写到D:\count.txt中...
用C语言编程实现统计D:\file.txt文件每个英文单词出现的频次,并按英文单词出现频次升序顺序将单词信息和频次信息写到D:\count.txt中
展开
1个回答
展开全部
#include <stdio.h>
#include <map>
#include <set>
using namespace std;
void main()
{
FILE* fp=fopen("D:\\count.txt","r");
if(fp)
{
map<string,int> str_count;
while(!feof(fp))
{
char buf[256]={};
fgets(buf,fp);
string word=buf;
if(word.isempty())
continue;
if(str_count.find(word)!=str_count.end())
str_count[word]=str_count[word]+1;
else
str_count[word]=1;
}
fclose(fp);
map<int,set<string> > count_wset;
for(map<string,int>::iterator iter=str_count.begin();iter!=str_count.end();++iter)
{
int count=(*iter).second;
string word=(*iter).first;
map<string,int>::iterator iset=count_wset.find(count);
if(count==count_wset.end)
{
set<string> set1;
set1.insert(word);
count_wset[count]=set1;
}
else
{
count_wset[count].insert(word);
}
}
FILE* fpo=fopen("D:\\count.txt","wb+");
if(fpo)
{
for(map<int,set<string> >::iter i=count_wset.rbegin();i!=count_wset.rend();++i)
{
int cc=(*i).first;
set<string>& words=(*i).second;
for(set<string>::ite=words.begin();ite!=words.end();++ite)
{
string aword=(*ite);
char tmp[512]={};
sprintf(tmp,"%s,%d\r\n",aword,cc);
fputs(tmp,fpo);
}
}
fclose(fpo);
}
}
}
#include <map>
#include <set>
using namespace std;
void main()
{
FILE* fp=fopen("D:\\count.txt","r");
if(fp)
{
map<string,int> str_count;
while(!feof(fp))
{
char buf[256]={};
fgets(buf,fp);
string word=buf;
if(word.isempty())
continue;
if(str_count.find(word)!=str_count.end())
str_count[word]=str_count[word]+1;
else
str_count[word]=1;
}
fclose(fp);
map<int,set<string> > count_wset;
for(map<string,int>::iterator iter=str_count.begin();iter!=str_count.end();++iter)
{
int count=(*iter).second;
string word=(*iter).first;
map<string,int>::iterator iset=count_wset.find(count);
if(count==count_wset.end)
{
set<string> set1;
set1.insert(word);
count_wset[count]=set1;
}
else
{
count_wset[count].insert(word);
}
}
FILE* fpo=fopen("D:\\count.txt","wb+");
if(fpo)
{
for(map<int,set<string> >::iter i=count_wset.rbegin();i!=count_wset.rend();++i)
{
int cc=(*i).first;
set<string>& words=(*i).second;
for(set<string>::ite=words.begin();ite!=words.end();++ite)
{
string aword=(*ite);
char tmp[512]={};
sprintf(tmp,"%s,%d\r\n",aword,cc);
fputs(tmp,fpo);
}
}
fclose(fpo);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询