二叉排序树实现英文文章单词统计
打开当目录下文件C:UsersAdministratorDesktopessay.txt,从中读取英文单词进行词频统计。输入单词查询个数和单词。
【输出形式】
输入一个单词按一下enter键,输出单词统计个数,输出一个单词及其出现次数,单词和其出现次数间由一个空格分隔,出现次数后无空格,直接为回车。
存储结构设计
typedef struct node{ int flag; int count; char word[26]; struct node *lchild, *rchild; }BTNode, *BTREE; 其中单词保持在Word数组中,建立节点的时候 每个节点有左孩子和右孩子 ,count记录单词出现数量
程序源文件
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> #define M 5000 typedef struct node{ int count; char word[26]; struct node *lchild, *rchild; //建立节点的时候 每个节点有左孩子和右孩子 }BTNode, *BTREE; int flag; int times = 0; int get_word(char *temp_word, FILE *in); BTREE insert(BTREE T, char temp_word[]); // remember to return a pointer so it can change its real address void inorder(BTREE root,char word[]); int main()//主函数入口 { char temp_word[26] = {0}; /*prepare to put the content of temp_word to real wordblock.word*/ char words[26] = {0}; int number; FILE *in; int i,j; if( (in = fopen("C:\Users\wpf\Desktop\essay.txt", "r")) == NULL )//打开文件 printf("No such file! "); BTREE root = NULL; //每次insert 都是把根节点当作参数传进去的 while( !feof(in) )//判断文件是否为空 { char temp_word[26] = {0}; get_word(temp_word,in);//从文件中找到一个单词保存在数组temp_word中 root = insert(root, temp_word);//构建二叉排序树,根节点为root } printf(" ******************************************************************************* "); //格式控制? printf(" 欢迎使用--文学研究助手。 "); printf("******************************************************************************* "); printf("你想查询单词的数量是:"); scanf("%d",&number); for (int i=0;i<number+1;i++) { if(i>0) printf("请输入目标单词;"); gets(words); char a[strlen(words)+1]; strcpy(a,words); if(i>0) { inorder(root,a); if(flag==0) { printf("单词%s在文章出现次数为 %d ", a, 0); flag=0; } } } return 0; } int get_word(char *temp_word, FILE *in)// 从文件中找到一个单词 保存在中数组 { int i = 0; char temp = 0; temp = fgetc(in);//从文件中得到一个字符 while( !isalpha(temp) )//当有字符时 { temp = fgetc(in); if(temp==EOF)//字符为空格 return 1;//返回 } while(isalpha(temp) && !isspace(temp) )//有字符且字符不为空格 { temp = tolower(temp); temp_word[i] = temp;//把字符保存在temp_word中 i++; temp = fgetc(in); } return 0; } BTREE insert(BTREE p, char temp_word[])//创建二叉排序树 { int cond; if(p == NULL)//如果节点p为空 { p = (BTREE)malloc(sizeof(BTNode));//给节点p分配空间 strcpy(p->word, temp_word);//把字符串temp_word复制到节点p保存单词数组中 p->count = 1;//记录单词数量为1 p->lchild = p->rchild = NULL;//p的左孩子右孩子为空 } else if( (cond = strcmp(temp_word, p->word)) == 0)//目标单词temp_word和 p->word想等 { p->count++;//p->word数量加一 } else if( cond<0 )//目标单词temp_word第一个字母比p->word第一个字母小 { p->lchild = insert(p->lchild, temp_word);//把目标单词插入到p左孩子中 } else//目标单词temp_word第一个字母比p->word第一个字母大 { p->rchild = insert(p->rchild, temp_word);//把目标单词插入到p右孩子中 } return (p); } void inorder(BTREE T, char word[]) //二叉树中序遍历 ,找到目标单词,输出 目标单词个数 { if(T!= NULL) { inorder(T->lchild,word); if(strcmp(word, T->word)==0) { printf("单词%s在文章出现次数为 %d ", T->word, T->count); flag=1; } inorder(T->rchild,word); } }
运行结果