C编程 实现 统计文件中各个单词出现的次数
已有文本文件test.txt 内容为 hello,how are you!Welcome you to China!编写一个程序读取test.txt。统计各单词出现次数,并将个单词和气出现的次数输出到屏幕和文件中.要求用C语言编程。 谢谢
程序代码:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct word {
char * words;
int count;
struct word * Next;
};
struct word_tab {
char alphaber;
struct word_tab *Next;
struct word *Word_Next;
};
int
index_word_tab( struct word_tab **p_total, char word[] );
void
print_word( struct word_tab **p_total );
int
getword( char word[], int n, FILE *fp );
int
main( void )
{
struct word_tab *p;
struct word_tab **kp;
char word1[ 50 ];
FILE *fp;
p = NULL;
kp = &p;
if( ( fp = fopen("word.txt","r") ) == NULL)
{
fprintf( stderr,"无法打开读取文件\n" );
exit( EXIT_FAILURE );
}
while( getword( word1, 50, fp ) > 0)
index_word_tab( kp, word1 );
print_word( kp );
fclose( fp );
getchar();
return 0;
}
int
getword( char word[], int n, FILE *fp )
{
int i, c;
while( ispunct( c = fgetc( fp ) ) )
;
for( i = 0; ( i < n - 1 ) && ( c != EOF ) && ( !isspace( c ) ); i++ )
{
word[ i ] = c;
c = fgetc( fp );
}
if( ispunct( word[ i - 1 ] ) && ( i - 1 ) > 0 )
{
word[ i - 1 ] = '\0';
return c;
}
word[ i ] = '\0';
return c;
}
int
index_word_tab( struct word_tab **p_total, char word[] )
{
int determine( char word[] );
struct word_tab * next;
struct word_tab * new_total;
struct word * next_word;
struct word * new_word;
struct word ** kNext;
char w;
if( word[ 0 ] == '\0')
return 0;
if( determine( word ) < 0 )
{
printf( "ERORR: %s\n", word );
return 0;
}
w = tolower( word[ 0 ] );
while( ( next = *p_total ) != NULL && next->alphaber < w )
p_total = &next->Next;
if( next == NULL || next->alphaber != w )
{
new_total = ( struct word_tab * )malloc( sizeof( struct word_tab ) );
if ( new_total == NULL )
return 0;
*p_total = new_total;
new_total->Next = next;
new_total->alphaber = w;
new_total->Word_Next = NULL;
}
kNext = &(*p_total)->Word_Next;
while ( ( next_word = *kNext ) != NULL && strcmp( next_word->words, word ) <= 0)
{
if ( strcmp( next_word->words, word ) == 0 )
{
next_word->count++;
return 0;
}
kNext = &next_word->Next;
}
new_word = ( struct word * )malloc( sizeof( struct word ) );
if ( new_word == NULL )
return 0;
*kNext = new_word;
new_word->Next = next_word;
new_word->count = 1;
new_word->words = strdup( word );
return 1;
}
void
print_word( struct word_tab **p_total )
{
struct word_tab *next;
struct word *word_next;
FILE *fp;
if( ( fp = fopen( "words.txt","w" ) ) == NULL )
{
fprintf( stderr,"无法打开写入文件\n" );
exit( EXIT_FAILURE );
}
while( ( next = *p_total ) != NULL )
{
for( word_next = next->Word_Next; word_next != NULL; word_next = word_next->Next )
fprintf( stdout, "%d %s %c", word_next->count, word_next->words,'\n' );
fprintf( stdout, "\n\n" );
p_total = &next->Next;
}
fclose( fp );
}
int
determine( char word[] )
{
int i,j;
j = strlen( word );
for( i = 0; isalpha( word[ i ] ) || ( i > 0 && ( word[ i ] == '\'' || word[ i ] == '-' ) ); i++ )
;
if(i == j)
return i;
else
return -1;
}
[此贴子已经被作者于2017-3-12 21:29编辑过]
