c - 有关二叉树的词频统计

查看:109
本文介绍了c - 有关二叉树的词频统计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

现在已经完成代码,可以读取文件中的单词,使其按字典序列输出,如何将其改成按单词出现频率由高至低输出
代码如下:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 50
struct tnode{
    char word[MAX];
    int count;
    struct tnode *left,*right;
}; 
struct tnode *treewords(struct tnode *,char *);
void treeprint(struct tnode *);
int main()
{
    char word[MAX];
    FILE *bfp;
    char c;
    int i;
    struct tnode *root;
    root=NULL;
    bfp=fopen("article.txt","r");
    while((c=fgetc(bfp))!=EOF){
        ungetc(c,bfp);
        for(i=0;(c=fgetc(bfp))!=' '&&c!='\n'&&c!=EOF;i++){
            if((c>='A'&&c<='Z')||(c>='a'&&c<='z')){
                c=tolower(c);
                word[i]=c;
            }else
                break;
        }
        word[i]='\0';
        if(strlen(word)>0)
            root=treewords(root,word);
    }
    treeprint(root);
    
    return 0;
}
struct tnode *treewords(struct tnode *p,char *w)
{
    int cond;
    if(p==NULL){
        p=(struct tnode*)malloc(sizeof(struct tnode));
        strcpy(p->word,w);
        p->count=1;
        p->left=p->right=NULL;
    }
    else if((cond=strcmp(w,p->word))==0){
        p->count++;
    }
    else if(cond<0){
        p->left=treewords(p->left,w);
    }
    else
        p->right=treewords(p->right,w);
    return (p);
}
void treeprint(struct tnode *p)
{
    if(p!=NULL){
        treeprint(p->left);
        printf("%s %d\n",p->word,p->count);
        treeprint(p->right);
    }
}

解决方案

  1. 将所有节点的指针放在一个数组里面(需要知道单词的个数,然后遍历二叉树获得这个数组)

  2. 使用任何一种排序方法根据词频排序

这篇关于c - 有关二叉树的词频统计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆