词频统计

做一个词频统计程序,该程序具有以下功能
基本要求:

(1)可导入任意英文文本文件

(2)统计该英文文件中单词数和各单词出现的频率(次数),并能将单词按字典顺序输出。

(3)将单词及频率写入文件。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct word
{
    char w[50];
    char temp[50]; //排序时用到的临时变量
    int count;
}t[100];

void main()
{
    char cl[150];
    int q=0;    //统计单词的长度
    int i=0;    //统计文件中的单词数
    int dele=0; //删除的单词数
    char *h[2]={"单词","出现的次数"}; //输出文件中的标题
    FILE *fp;
    if((fp=fopen("in.txt","r"))==NULL)
        exit(1);
    while(fscanf(fp,"%s",cl)==1)
    {
        printf("%s ",cl);
        strcpy(t[i].w,cl);
        i++;
    }
    fclose(fp);  //关闭文件
    printf("\n\n");
    printf("该文章共有%d个单词。",i);
    printf("\n\n");
    //查找文章中相同的单词,并把后面相同的单词删掉,依次往前挪一个
    for(int j=0;j<i;j++)
    {
        for(int k=j+1;k<i;k++)
        {
        if(strcmp(t[j].w,t[k].w)==0)
        {
            t[j].count++;
            dele++;
            int m=k;
            while(m<i)
            {
                strcpy(t[m].w,t[m+1].w);
                m++;
            }
        }
        }
    }
    //排序
    for(int n=0;n<i-dele;n++)
    {
        for(int a=n+1;a<i-dele;a++)
        {
        if(strcmp(t[n].w,t[a].w)>0)
        {
            strcpy(t[0].temp,t[n].w);
            strcpy(t[n].w,t[a].w);
            strcpy(t[a].w,t[0].temp);
            t[n].count=t[n].count+t[a].count;
            t[a].count=t[n].count-t[a].count;
            t[n].count=t[n].count-t[a].count;
        }
        }
    }
    //输出
    for(int b=0;b<i-dele;b++)
    {
        printf("%s:   ",t[b].w);
        printf("%d次",t[b].count+1);
        printf("\n");
    //写入文件
    fp=fopen("out.txt","w");
    for(int p=0;p<2;p++) //在文件中显示标题栏
    {     
        fputs(h[p],fp);fputs("          ",fp);
    }
    fputs("\n",fp);
    for(int b=0;b<i-dele;b++){     //在文件中显示单词和出现的次数
        q=strlen(t[b].w);
        fputs(t[b].w,fp);
        for(int g=0;g<16-q;g++)
        fputs(" ",fp);
        fprintf(fp,"%d",t[b].count+1);fputs("\n",fp);
                            }
    fclose(fp);  //关闭文件
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值