请编写程序,对一段英文文本,统计其中所有不同单词的个数,以及词频最大的前10%的单词。 所谓“单词”,是指由不超过80个单词字符组成的连续字符串,但长度超过15的单词将只截取保留前15个单词字符。而合法的“单词字符”为大小写字母、数字和下划线,其它字符均认为是单词分隔符。 输入格式: 输入给出一段非空文本,最后以符号#结尾。输入保证存在至少10个不同的单词。 输出格式: 在第一行中输出文本中所有不同单词的个数。注意“单词”不区分英文大小写,例如“PAT”和“pat”被认为是同一个单词。 随后按照词频递减的顺序,按照词频:单词的格式输出词频最大的前10%的单词。若有并列,则按递增字典序输出。使用c
时间: 2023-06-16 21:02:03 浏览: 140
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX_WORD_LENGTH 80
#define MAX_WORD_COUNT 100000
struct Word {
char word[MAX_WORD_LENGTH + 1];
int count;
};
struct Word words[MAX_WORD_COUNT];
int compare(const void *a, const void *b) {
const struct Word *x = (const struct Word *)a;
const struct Word *y = (const struct Word *)b;
if (x->count != y->count) {
return y->count - x->count;
} else {
return strcmp(x->word, y->word);
}
}
int main() {
char c;
int wordCount = 0;
int totalCount = 0;
char word[MAX_WORD_LENGTH + 1];
int i, j;
memset(words, 0, sizeof(words));
while ((c = getchar()) != '#') {
if (isalnum(c) || c == '_') {
if (wordCount < MAX_WORD_LENGTH) {
word[wordCount++] = tolower(c);
}
} else {
if (wordCount > 0) {
if (wordCount > 15) {
wordCount = 15;
}
word[wordCount] = '\0';
int found = 0;
for (i = 0; i < totalCount; i++) {
if (strcmp(words[i].word, word) == 0) {
words[i].count++;
found = 1;
break;
}
}
if (!found) {
if (totalCount < MAX_WORD_COUNT) {
strcpy(words[totalCount].word, word);
words[totalCount].count = 1;
totalCount++;
}
}
wordCount = 0;
}
}
}
qsort(words, totalCount, sizeof(struct Word), compare);
printf("%d\n", totalCount);
int topCount = totalCount / 10;
if (topCount == 0) {
topCount = 1;
}
int maxCount = words[0].count;
for (i = 0; i < totalCount && words[i].count >= maxCount / topCount; i++) {
printf("%d:%s\n", words[i].count, words[i].word);
}
return 0;
}
```
阅读全文