我在互联网上找到了这个巨大的代码。它是一个程序,可以在文件中找到n个最常用的单词并打印出来。下面的程序读取给定的文本文件,但我想自己编写输入文本,所以我可能会将这些单词存储在一个数组中。我该怎么做才能让程序读取随机长度的文本,以下程序仍然可以工作?而且如果输入文本中有标点符号,我将不得不删除它们,因此文本不会只包含来自' a'的字母。到了'。我甚至需要MAX_CHARS
常数吗?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
# define MAX_CHARS 26
# define MAX_WORD_SIZE 32000
// A utility function to show results, The min heap
// contains n most frequent words so far, at any time
void displayMinHeap( MinHeap* minHeap )
{
int i;
// print top N word with frequency
for( i = 0; i < minHeap->count; ++i )
{
printf( "%s %d\n", minHeap->array[i].word,
minHeap->array[i].frequency );
}
}
// The main funtion that takes a file as input, add words to heap
// and Trie, finally shows result from heap
void printKMostFreq( FILE* fp, int n )
{
// Create a Min Heap of Size n
MinHeap* minHeap = createMinHeap( n );
// Create an empty Trie
TrieNode* root = NULL;
// A buffer to store one word at a time
char buffer[MAX_WORD_SIZE];
// Read words one by one from file. Insert the word in Trie and Min Heap
while( fscanf( fp, "%s", buffer ) != EOF )
insertTrieAndHeap(buffer, &root, minHeap);
// The Min Heap will have the n most frequent words, so print Min Heap nodes
displayMinHeap( minHeap );
}
int main()
{
int n;
scanf("%d", &n);
FILE *fp = fopen ("file.txt", "r");
if (fp == NULL)
printf ("File doesn't exist ");
else
printKMostFreq (fp, n);
return 0;
}
答案 0 :(得分:0)
可以修改此程序以执行您想要的操作,但我不打算为您执行此操作,至少在没有付款的情况下是这样。对于简单的解决方案,请尝试生成文本并将其写入文本文件。然后,您可以将该文件的内容传递到单词计数软件中。你也可以使用管道来做到这一点。