C语言实现英文文章单词拼写检查
C语言实现英文文章单词拼写检查
功能描述
本程序读取一个单词索引表和一个英文文章,检查文章中每个单词的拼写,并将拼写错误的单词输出到另一个文件中。程序支持大小写不敏感的检查,并处理格式杂乱的文章。
程序代码c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>
#define MAX_WORD_LEN 50#define MAX_WORDS_NUM 1000
// 读取单词索引表int readIndex(char index[MAX_WORDS_NUM][MAX_WORD_LEN+1]) { FILE *fp = fopen('index.txt', 'r'); if (fp == NULL) { printf('Failed to open index.txt '); return -1; } int i = 0; while (fgets(index[i], MAX_WORD_LEN+1, fp) != NULL) { // 去掉行末的换行符 index[i][strlen(index[i])-1] = '�'; i++; } fclose(fp); return i;}
// 判断单词是否在索引表中int isInIndex(char *word, char index[MAX_WORDS_NUM][MAX_WORD_LEN+1], int indexSize) { int left = 0, right = indexSize-1, mid; while (left <= right) { mid = (left + right) / 2; int cmp = strcmp(word, index[mid]); if (cmp == 0) { return 1; } else if (cmp < 0) { right = mid - 1; } else { left = mid + 1; } } return 0;}
// 将单词转换为小写void toLower(char *word) { while (*word != '�') { *word = tolower(*word); word++; }}
int main() { char index[MAX_WORDS_NUM][MAX_WORD_LEN+1]; int indexSize = readIndex(index); if (indexSize == -1) { return 1; }
FILE *fpIn = fopen('in.txt', 'r'); if (fpIn == NULL) { printf('Failed to open in.txt
'); return 1; } FILE *fpErr = fopen('error.txt', 'w'); if (fpErr == NULL) { printf('Failed to create error.txt '); return 1; }
char word[MAX_WORD_LEN+1]; int wordLen = 0; int c; while ((c = fgetc(fpIn)) != EOF) { if (isalpha(c)) { word[wordLen++] = c; if (wordLen > MAX_WORD_LEN) { // 单词长度超过限制,忽略该单词 wordLen = 0; } } else { if (wordLen > 0) { // 处理完整的单词 word[wordLen] = '�'; toLower(word); if (!isInIndex(word, index, indexSize)) { fprintf(fpErr, '%s
', word); } wordLen = 0; } } } // 处理最后一个单词 if (wordLen > 0) { word[wordLen] = '�'; toLower(word); if (!isInIndex(word, index, indexSize)) { fprintf(fpErr, '%s ', word); } }
fclose(fpIn); fclose(fpErr); return 0;}
使用说明
- 将程序代码保存为
spell_check.c文件。2. 在程序所在目录下创建index.txt文件,并将单词索引表按照字典序由小到大排列,每个单词独占一行。3. 在程序所在目录下创建in.txt文件,并将需要进行拼写检查的英文文章写入该文件。4. 编译程序:gcc spell_check.c -o spell_check5. 运行程序:./spell_check6. 程序运行结束后,会在程序所在目录下生成error.txt文件,其中包含所有拼写错误的单词,每个单词独占一行,并按照字典序由小到大的顺序输出。
注意
index.txt中的单词个数不超过 1000 个,每个单词的长度不超过 50 个字母。*in.txt中的文章有可能没有经过排版,格式有可能杂乱无章,也有可能没有写完整。* 若出错的单词多次出现,则多次输出。
原文地址: https://www.cveoy.top/t/topic/glZW 著作权归作者所有。请勿转载和采集!