英文文章单词正确性检查工具 - 基于索引词库的错误单词识别
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h>
#define MAX_WORD_LEN 50 #define MAX_INDEX_WORDS 1000
int compare(const void *a, const void b) { return strcmp((const char **)a, *(const char **)b); }
int main() { char index_words[MAX_INDEX_WORDS][MAX_WORD_LEN + 1]; // 单词索引表 char error_words[MAX_INDEX_WORDS][MAX_WORD_LEN + 1]; // 出错的单词 int index_word_count = 0; // 单词索引表中单词的数量 int error_word_count = 0; // 出错的单词的数量
// 读取单词索引表
FILE *index_file = fopen('index.txt', 'r');
if (index_file == NULL) {
printf('无法打开文件index.txt\n');
return 1;
}
char word[MAX_WORD_LEN + 1];
while (fscanf(index_file, '%s', word) == 1) {
for (int i = 0; word[i]; i++) {
word[i] = tolower(word[i]); // 转换为小写字母
}
strcpy(index_words[index_word_count], word);
index_word_count++;
}
fclose(index_file);
// 对单词索引表进行排序
qsort(index_words, index_word_count, sizeof(index_words[0]), compare);
// 读取英文文章并检查单词正确性
FILE *in_file = fopen('in.txt', 'r');
if (in_file == NULL) {
printf('无法打开文件in.txt\n');
return 1;
}
char c;
int word_len = 0;
char current_word[MAX_WORD_LEN + 1];
while ((c = fgetc(in_file)) != EOF) {
if (isalpha(c)) { // 如果是字母
if (word_len < MAX_WORD_LEN) {
current_word[word_len] = tolower(c); // 转换为小写字母
word_len++;
}
} else { // 如果不是字母
if (word_len > 0) { // 如果当前有单词
current_word[word_len] = '\0'; // 添加字符串结束符
// 在单词索引表中查找当前单词
int left = 0, right = index_word_count - 1;
while (left <= right) {
int mid = (left + right) / 2;
int cmp = strcmp(current_word, index_words[mid]);
if (cmp < 0) {
right = mid - 1;
} else if (cmp > 0) {
left = mid + 1;
} else { // 找到了当前单词
goto found;
}
}
// 没有找到当前单词,加入出错的单词列表
strcpy(error_words[error_word_count], current_word);
error_word_count++;
found:
word_len = 0; // 重置当前单词长度
}
}
}
fclose(in_file);
// 输出出错的单词
if (error_word_count > 0) {
// 对出错的单词进行排序
qsort(error_words, error_word_count, sizeof(error_words[0]), compare);
// 输出到文件error.txt
FILE *error_file = fopen('error.txt', 'w');
if (error_file == NULL) {
printf('无法创建文件error.txt\n');
return 1;
}
for (int i = 0; i < error_word_count; i++) {
fprintf(error_file, '%s\n', error_words[i]);
}
fclose(error_file);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/gmiB 著作权归作者所有。请勿转载和采集!