BUAA_数据结构_5TH_2. 词频统计(树实现)
第五次作业链接
1. 树叶节点遍历(树-基础题)
3. 计算器(表达式计算-表达式树实现)
4. 网络打印机选择
题目描述:
编写程序统计一个英文文本文件中每个单词的出现次数(词频统计),并将统计结果按单词字典序输出到屏幕上。
要求:程序应用二叉排序树(BST)来存储和统计读入的单词。
注:在此单词为仅由字母组成的字符序列。包含大写字母的单词应将大写字母转换为小写字母后统计。在生成二叉排序树不做平衡处理。
输入形式
打开当前目录下文件article.txt,从中读取英文单词进行词频统计。
输出形式
程序应首先输出二叉排序树中根节点、根节点的右节点及根节点的右节点的右节点上的单词(即root、root->right、root->right->right节点上的单词),单词中间有一个空格分隔,最后一个单词后没有空格,直接为回车(若单词个数不足三个,则按实际数目输出)。
程序将单词统计结果按单词字典序输出到屏幕上,每行输出一个单词及其出现次数,单词和其出现次数间由一个空格分隔,出现次数后无空格,直接为回车。
样例输入
当前目录下文件article.txt内容如下:
“Do not take to heart every thing you hear.”
“Do not spend all that you have.”
“Do not sleep as long as you want;”
样例输出
do not take
all 1
as 2
do 3
every 1
have 1
hear 1
heart 1
long 1
not 3
sleep 1
spend 1
take 1
that 1
thing 1
to 1
want 1
you 3
易错点
1.strcmp函数的使用
2.输出形式
参考代码
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#define maxn 25
typedef struct tree{
char word[maxn];
struct tree *lc,*rc;
int time;
}tree,*tree_ptr;
tree_ptr root;
char Article[10010];
char word_temp[maxn];
void clear_word_temp();
char lower_to_upper(char x);
tree_ptr create_node(char word_temp[]);
tree_ptr add(tree_ptr now,char word_temp[]);
void Middle(tree_ptr temp);
int main()
{
FILE *in;
in=fopen("article.txt","r");
int Article_lenth;
Article_lenth=fread(Article,1,10010,in);
Article_lenth=strlen(Article);
fclose(in);
clear_word_temp();
int word_pos=0;
for(int i=0;i<Article_lenth;i++){
if(isalpha(Article[i])){
word_temp[word_pos]=lower_to_upper(Article[i]);
word_pos++;
}
else if(word_pos==0) ;
else{
root=add(root,word_temp);
word_pos=0;
clear_word_temp();
}
}
if(root){
printf("%s",root->word);
if(root->rc){
printf(" %s",root->rc->word);
if(root->rc->rc){
printf(" %s\n",root->rc->rc->word);
}
else{
printf("\n");
}
}
else{
printf("\n");
}
}
Middle(root);
return 0;
}
void clear_word_temp()
{
for(int j=0;j<25;j++){
word_temp[j]='\0';
}
}
char lower_to_upper(char x)
{
return (x>='A'&&x<='Z')?(x|0x20):x;
}
tree_ptr create_node(char word_temp[])
{
tree_ptr temp=(tree_ptr)malloc(sizeof(tree));
temp->lc=NULL;
temp->rc=NULL;
temp->time=1;
strcpy(temp->word,word_temp);
return temp;
}
tree_ptr add(tree_ptr now,char word_temp[])
{
if(now==NULL){
now=create_node(word_temp);
}
else if(strcmp(word_temp,now->word)==0){
now->time++;
}
else if(strcmp(word_temp,now->word)<0){
now->lc=add(now->lc,word_temp);
}
else if(strcmp(word_temp,now->word)>0){
now->rc=add(now->rc,word_temp);
}
return now;
}
void Middle(tree_ptr temp)
{
if(temp->lc){
Middle(temp->lc);
}
printf("%s %d\n",temp->word,temp->time);
if(temp->rc){
Middle(temp->rc);
}
}
有问题
或bug欢迎私戳/评论