题目描述:
文本文件由若干英文单词和分隔符(空格,回车,换行)构成。根据如下说明编写程序统计不同单词出现的次数 (频度)。将统计结果按出现频度从高到低排序,并将出现频度大于5的单词及其频度输出到文件output.txt中。文件格式如图1所示。
说明:
(1)多个连续的分隔符被视为一个分隔符。
(2)单词大小写敏感。
(3)每个单词的长度不超过20个字符。
(4)单词的数量未知。如使用定义静态大数组的方式来统计,将被扣除5分。
输入描述:
The constructor is used to initialize the object The destructor is used to delete the Object the calling sequence of constructor is opposite to the calling sequence of destructor
输出描述:
the,4
to,3
is,3
used,2
constructor,2
The,2
destructor,2
calling,2
sequence,2
of,2
Object,1
object,1
initialize,1
delete,1
opposite,1
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void input(struct WordNode *head);
void output(struct WordNode *head);
void calculate(struct WordNode *head);
void sort(struct WordNode *head);
struct WordNode{
char word[20];
struct WordNode *wd;
int frequence;
};
void main(){
struct WordNode *head;
head=(struct WordNode*)malloc(sizeof(struct WordNode));
head->wd=NULL;
input(head);
calculate(head);
sort(head);
output(head);
}
void input(struct WordNode *head){
FILE *fp;
struct WordNode *p;
char temp[20];
p=(struct WordNode*)malloc(sizeof(struct WordNode));
p=head;
if((fp=fopen("D:\\2019Post\\pat\\pat\\data2016.txt","r"))==NULL){
printf("can not open the file");
exit(0);
}
while(!feof(fp)){
struct WordNode* newnode;
newnode=(struct WordNode*)malloc(sizeof(struct WordNode));
fscanf(fp,"%s",temp);
strcpy(newnode->word,temp);
newnode->frequence=1;
newnode->wd=NULL;
p->wd=newnode;
p=p->wd;
}
fclose(fp);
}
void output(struct WordNode *head){
FILE *fa;
struct WordNode *p;
p=(struct WordNode*)malloc(sizeof(struct WordNode));
p=head;
if((fa=fopen("D:\\2019Post\\pat\\pat\\output2016.txt","w"))==NULL){
printf("can not open the file");
exit(0);
}
while(p->wd!=NULL){
fprintf(fa,"%s,",p->wd->word);
fprintf(fa,"%d\n",p->wd->frequence);
p=p->wd;
}
fclose(fa);
}
void calculate(struct WordNode *head){
struct WordNode *p=(struct WordNode*)malloc(sizeof(struct WordNode));
struct WordNode *q=(struct WordNode*)malloc(sizeof(struct WordNode));
p=head->wd;
q=p;
while(p!=NULL){
while(q->wd!=NULL){
if(strcmp(p->word,q->wd->word)==0){
p->frequence++;
q->wd=q->wd->wd;
}else{
q=q->wd;
}
}
p=p->wd;
q=p;//记得复位
}
}
void sort(struct WordNode *head){
struct WordNode *p=(struct WordNode*)malloc(sizeof(struct WordNode));
struct WordNode *q=(struct WordNode*)malloc(sizeof(struct WordNode));
p=head->wd;
q=p;
while(p!=NULL){
while(q->wd!=NULL){
if(p->frequence<q->frequence){
char tempword[20];
int tempfrequence;
strcpy(tempword,p->word);
tempfrequence=p->frequence;
strcpy(p->word,q->word);
p->frequence=q->frequence;
strcpy(q->word,tempword);
q->frequence=tempfrequence;
}
q=q->wd;
}
p=p->wd;
q=p;
}
}