编程统计一个英文文本文件中单词词频

5.编程统计一个英文文本文件中单词词频,并按词频的降序排序后输出所有单词。请写出主函数的算法描述。输入并调试完整的单词词频程序。

#include

#include 

struct LNode{

char data[1024];

int word_fre;

struct LNode *next;

};

struct LNode *create()

{

struct LNode *head,*p,*rear,*s;

FILE *file1;

int i,j=0,k=0,m=1,l=0,n=0;

char c[1024];

file1=fopen("f:\\file1.txt","r");

while(fgets(c,1024,file1)!=NULL)

{

puts(c);

}

head=(struct LNode *)malloc(sizeof(struct LNode));

rear=head;

    p=(struct LNode *)malloc(sizeof(struct LNode));

// printf("\n我爱你:%c\n",p->data[1]);

p->data[0]='0';

for(i=0;c[i]!='\0';i++)

{

    

if(c[i]>='a'&&c[i]<='z'||c[i]>='A'&&c[i]<='Z')

{

// printf("1\n");

p->data[j]=c[i];

// printf("%c",p->data[j]);

j++;

}else{

if(p->data[0]!='0'){

p->data[j]='\0';

// printf("%s ",p->data);

j=0;

rear->next=p;

rear=p;

p=(struct LNode *)malloc(sizeof(struct LNode));

}

p->data[0]='0';

}

}

if(p->data[0]!='0'){

p->data[j]='\0';

// printf("%s ",p->data);

j=0;

rear->next=p;

rear=p;

p=(struct LNode *)malloc(sizeof(struct LNode));

}

rear->next=NULL;

printf("各单词为:\n");

n=0;

for(p=head->next;p!=NULL;p=p->next)

{

n++;

printf("%s ",p->data);

}

// printf("...");

printf("\n%d\n",n);

fclose(file1);

return head;

}

 

bool equal(struct LNode *p1,struct LNode *p2)

{

int i,j;

for(i=0;p1->data[i]!='\0',p2->data[i]!='\0';i++)

{

if(p1->data[i]!=p2->data[i])

return false;

}

if(p1->data[i]!='\0' || p2->data[i]!='\0')

return false;

return true;

}

struct LNode * wordFre(struct LNode *p)

{

int i=0,j,n=1;

struct LNode *r,*q,*t,*s;

s=p;

p=p->next;

for(r=p;r!=NULL;r=r->next)

{

t=r;

i++;

printf("%s ",r->data);

q=r->next;

while(q!=NULL)

{

// printf("%d ",1);

if(equal(r,q))

{

n++;

t->next=q->next;

q=t;

}else{

t=q;

}

q=q->next;

}

printf("%d ",n);

r->word_fre=n;

n=1;

}

// printf("%d\n",i);

printf("\n各单词的词频为:\n");

for(r=p;r!=NULL;r=r->next)

{

printf("%s:%d   ",r->data,r->word_fre);

}

printf("\n");

return s;

}

void nodeSeq(struct LNode *p)

{

struct LNode *q,*t,*r,*s;

int n=0,i;

for(q=p->next;q!=NULL;q=q->next)

n++;

printf("\n");

for(i=n;i>=1;i--)

{

t=p;

for(q=p->next;q->next!=NULL;q=q->next)

{

if(q->word_frenext->word_fre)

{

s=q->next;

t->next=s;

q->next=s->next;

s->next=q;

q=s;

          //  printf("%d\n",s->word_fre);

// printf("...\n");

}

t=q;

// printf("%d\n",q->word_fre);

}

}

printf("排序后的单词为:\n");

for(q=p->next;q!=NULL;q=q->next)

{

printf("%s:%d  ",q->data,q->word_fre);

}

printf("\n");

}

void main()

{

struct LNode *p,*q;

p=create();

q=wordFre(p);

nodeSeq(q);

}

 

你可能感兴趣的:(c)