统计英文文档中重复次数最多的前1000个单词,按重复次数从大到小输出,并保存到文件
#include
#include
#include
#include
#include
#define WORD_LEN 100
#define INIT_SIZE 10typedef struct Word
{char str[WORD_LEN];int count;
}Word;typedef struct WordTable
{Word* elem;int usedsize;int len;
}WordTable;void InitWordTable(WordTable* pwt)
{assert(pwt != NULL);pwt->elem = (Word*)malloc(sizeof(Word) * INIT_SIZE);pwt->usedsize = 0;pwt->len = INIT_SIZE;
}
int Search(WordTable* pwt, const char* newWord)
{for (int i = 0; i < pwt->usedsize; i++){if (strcmp(pwt->elem[i].str, newWord) == 0){return i;}}return -1;
}
bool InsertWord(WordTable* pwt, const char* newWord)
{if (pwt->usedsize == pwt->len){pwt->len *= 2;pwt->elem = (Word*)realloc(pwt->elem, pwt->len * sizeof(Word));assert(pwt->elem != NULL);}strcpy(pwt->elem[pwt->usedsize].str, newWord);pwt->elem[pwt->usedsize].count = 1;pwt->usedsize++;return true;
}void SaveWord(WordTable* pwt, const char* newWord)
{int i = Search(pwt, newWord);if (i != -1){pwt->elem[i].count++;}else{InsertWord(pwt, newWord);}
}
void Destroy(WordTable* pwt);
void BubbleSort(WordTable* pwt)
{Word tmp;for (int i = 0; i < pwt->usedsize - 1; i++){for (int j = 0; j + 1 < pwt->usedsize - i; j++){if (pwt->elem[j].count < pwt->elem[j + 1].count){tmp = pwt->elem[j];pwt->elem[j] = pwt->elem[j + 1];pwt->elem[j + 1] = tmp;}}}
}
void WriteFile(WordTable* pwt, int len)
{const char* path = "temp.txt";assert(pwt != NULL && len > 0);len = len < pwt->usedsize ? len : pwt->usedsize;FILE* fw = fopen(path, "w");assert(fw != NULL);char arr[WORD_LEN + 20];for (int i = 0; i < len; i++){sprintf(arr, "%s出现的次数:%d\n", pwt->elem[i].str, pwt->elem[i].count);fwrite(arr, sizeof(char), strlen(arr), fw);}fclose(fw);
}
void Show(WordTable* pwt)
{assert(pwt != NULL);int len = pwt->usedsize < 1000 ? pwt->usedsize : 1000;for (int i = 0; i < len; i++){printf("%s出现的次数:%d\n", pwt->elem[i].str, pwt->elem[i].count);}
}
void ReadWord(const char* path)
{FILE* fr = fopen(path, "r");assert(fr != NULL);char ch;char newWord[WORD_LEN];int i = 0;bool flg = false;WordTable wt;InitWordTable(&wt);while (fread(&ch, sizeof(char), 1, fr) > 0){if (isalpha((unsigned char)ch)){newWord[i++] = ch;flg = true;}else{if (flg){newWord[i] = '\0';SaveWord(&wt, newWord);flg = 0;i = 0;}}}fclose(fr);BubbleSort(&wt);WriteFile(&wt, 1000);
}int main()
{ReadWord("Harry Poter.txt");return 0;
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!