《词频统计 C代码.docx》由会员分享,可在线阅读,更多相关《词频统计 C代码.docx(3页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。
1、词频统计排序统计英文文献中的词频,并排序作业单词统计局部采用字典树的方法将单词分类并统计,然后采用字典树的遍历将字典 树统计的字符按顺序拼接并将词频读出统一存入数组中,最后采用冒泡排序的方法将数组中 的词频按从小到大的顺序排列并输出到文件中。源代码:include include #include define MAX 27/26 个字母和,字典树的结构体定义typedef struct Word(Word*nextMAX; 数组下标525代表小写字母,26 int num;);结构体定义:单词和对应频率typedef struct tlist(char word200;int time;);
2、struct tlist list(3000000;Word *root;charstr2OO=;char tempword1000;int size=0;新建单词的函数void createWord(char *str)(int len = strlen(str), id;Word *p = root, *q;for(int i = 0; i = a & stri = A & stri nextid = NULL)假设已到达链表结尾,开辟新的结构体存入字母 q = (Word *)malloc(sizeof(Word);for(int j = 0; j num=O;q-nextj = NUL
3、L;p-nextid) = q;p = p-nextid;)else假设未到达链表结尾,指针指向下一个(p = p-nextid;)p-num+;)读单词的函数void readWordfWord *p,int len)(int i;for(i=0;inexti!=NULL)if (i=26)strlen+l|=O;strlen)=;len+;else(strlen=,a+i;len+;)readWord(Word*)p-nexti,len);len-;)if(p-num!=0)strlen=0;strcpy(listsize.word,str);如果遇到单词结束标志,将 str 存入 lis
4、tsize.word Iistsize).time=p-num;size+;)主程序int main()(root=(Word*)malloc(sizeof(Word);int i,j;for (i=0;inexti=NULL;FILE *fp;char x;int len=0;fp=fopen(text.txt;r);while(x=fgetc(fp)!=EOF) 从 txt 文档中读入 (if (x=A&x=a,&x=z)| |(x=&len;=0)tempwordlen=x;len+;else tempwordlen=0;createWord(tempword);len=0;)tempw
5、ord(len=0;createWord(tempword);len=0;fclose(fp);readWord(root,0);比拟频率大小冒泡排序struct tlist temp;for(i=0;isize-l;i+)for(j=i+l;jlistj.time| |(listi.time=listj.time&strcmp(listi.wordjistj.word)0) (temp.time=listi.time;listi.time=listj.time;listj.time=temp.time;strcpy(temp.wordjisti.word);strcpy(listi.wordjistj.word);strcpyflistUJ.wordtemp.word);)将单词和对应频率输出到result.txt中FILE *fpx;fpx=fopen(result.txt/w);for (i=0;isize;i+) fprintf(fpx,%s %dnjisti.wordjisti.time); fclose(fpx);return 0;)
限制150内