统计单词个数并排序(C with stl)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
const int MAXN = 2000000;//文章的最大字符数
const int MAXW = 20;//单词的最大字符数
bool isletter(char c);

struct Word
{
	char word[MAXW];
	int n;
}word[MAXN];
Word filted_word[MAXN];
bool cmp1(Word x, Word y);
bool cmp2(Word x, Word y);
char passage;//文章
int main()
{
	//输入输出文件指针
	//fclose(fopen("input.txt","a")); 
	FILE* fpr = fopen("input.txt", "r");
	FILE* fpw = fopen("output.txt", "w");
	int i;
	if (fpr)
	{
		int flag = 0;
		int i1 = 0, i2 = 0;
		passage = fgetc(fpr);
		for (; feof(fpr)!= 1;)
		{
			while (isletter(passage)&& feof(fpr) != 1)//第一种选择,i是字母,则循环直到i遇到第一个空格,或者达到文章末尾为止
			{
				word[i1].word[i2] = (passage>='A'&&passage<='Z')?(passage+('a'-'A')):(passage);//i1代表记录了第几个单词,i2表示记录了该单词的第几个字符(只记录小写)
				
				i2++;
				passage = fgetc(fpr);
				if (isletter(passage) == 0)//如果刚好达到临界点
				{
					i1++;//准备记录下一个单词
					i2 = 0;//字符清零
				}
			}
			while (isletter(passage) == 0&& feof(fpr) != 1)//第二种选择,i不是字母,则循环直到i遇到第一个字母为止
			{
				passage = fgetc(fpr);
			}
		}

		printf("i1=%d\n", i1);
		//单词记录完毕
		int n1 = i1, n2 = 0;//n1代表未筛选时的单词数目 , n2代表筛选后的单词数目
		sort(word, word + n1-1, cmp1);

		int ct_filted_word = 0;
		for (i = 0; i <= n1 - 1; )
		{
			int ct = 1;
			while (i <= n1 - 1 && strcmp(word[i].word, word[i + 1].word) == 0)
			{
				ct++; i++;
			}
			if (strcmp(word[i].word, word[i + 1].word) != 0)
			{
				strcpy(filted_word[ct_filted_word].word, word[i].word);
				filted_word[ct_filted_word].n = ct;
				ct = 1;
				i++;
				ct_filted_word++;
			}
		}
		n2 = ct_filted_word;
		sort(filted_word, filted_word + n2, cmp2);
		if (fpw)
		{
			for (i = 0; i <= n2 - 1; i++)
				fprintf(fpw, "单词:%s       词频%d\n", filted_word[i].word, filted_word[i].n);
			return 0;
		}
		else
		{
			printf("写文件读取失败\n");
		}




	}
	else
	{
		printf("读文件打开失败\n");
		return 0;
	}
}
bool isletter(char c)//判断c是不是字母
{
	if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
		return 1;
	else
		return 0;
}
bool cmp1(Word x,Word y)
{
	if(strcmp(x.word, y.word)==0)	return 0;
	return ((strcmp(x.word, y.word) < 0) ? (1) : (0));
}
bool cmp2(Word x, Word y)
{
	return (x.n > y.n) ? (1) : (0);
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值