分析一个文本文件中各个单词出现的频率,把频率最高的10个词打印出来
分析:
(1)刚看到这个问题作为我们计算机人的第一反应应该是该用什么样的算法来实现,一使用数组,二使用链表,我觉得链表更好些,可以节约空间也不用改参数
(2)这个题的思路:先读文件,遍历分析单词频率,排序,输出
(3)语言:C语言
(4)其实刚开始我用的是数组,因为觉得链表比较麻烦,但结果用数组做的程序的质量总是不让人满意,有时要改参数,还有一些数组越界的问题,
于是我查了查网上和其他同学的做法,他们多数用的是链表,而且不会存在数组越界的问题让人豁然开朗。我有对程序进行了改进,该用链表的做法
(5)实践出真知,动手才会发现问题,然后自己分析,请教别人解决问题,在这其中也是乐趣多多哈。
(6)如有问题,请指正,下面是程序代码,运行结果。
程序代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | #include "stdafx.h"//头文件 #include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<string.h> struct fenxi { char zifu[30]; int m; struct fenxi *next; }; int main() //主函数 { struct fenxi *Head=NULL; struct fenxi*q; FILE *fp; int i; int a[10]; char b; for (i=0;i<10;i++) a[i]=0; fp=fopen( "d://fenxi.txt" , "r" );//读文件 while (!feof(fp)) { char *p=( char *)malloc(30* sizeof ( char )); fscanf(fp, "%s" ,p); if (Head==NULL) //分析单词频率 { struct fenxi *temp=( struct fenxi*)malloc( sizeof ( struct fenxi)); strcpy(temp->zifu,p); temp->m=1; temp->next=NULL; Head=temp; } else { struct fenxi *L=Head; while (L!=NULL) { if (strcmp(L->zifu,p)==0) { int count = L->m; count++; L->m = count; break ; } L=L->next; } if (L==NULL) { struct fenxi*temp = ( struct fenxi*)malloc( sizeof ( struct fenxi)); strcpy(temp->zifu, p); temp->m=1; temp->next=Head; Head=temp; } } } printf( "单词出现频率由高到低:\n" ); //排序输出 for (i=0;i<10;i++) { q=Head; while (q!=NULL) { if (q->m>a[i]) a[i]=q->m; else q=q->next; } q=Head; while (q!=NULL) { if (a[i]==q->m) { q->m=0;printf( "%s\t\n" ,q->zifu); printf( "单词出现频率:%d\t\n" ,a[i]); break ; } else q=q->next; } } return 0; } |
运行结果:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步