C语言实现英文文章单词正确性检查:利用索引表识别错误单词

本程序使用一个预先存在的正确单词索引表,对给定的英文文章进行单词正确性检查。程序将识别出文章中所有不在索引表中的单词,并以字典序输出到一个错误文件error.txt中。

思路:

  1. 读取单词索引表,存储到一个字符串数组中,注意将所有单词转换为小写字母。
  2. 读取英文文章,逐个单词进行比较,若不在单词索引表中,则将该单词转换为小写字母并存储到一个字符串数组中。
  3. 对存储错误单词的字符串数组进行字典序排序。
  4. 将排序后的字符串数组输出到error.txt文件中。

代码实现:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_WORDS 1000
#define MAX_WORD_LEN 50

int main() {
    // 读取单词索引表
    FILE *fp_index = fopen("index.txt", "r");
    if (fp_index == NULL) {
        perror("Error opening index.txt");
        return 1;
    }
    char index_words[MAX_WORDS][MAX_WORD_LEN];
    int word_count = 0;
    while (fscanf(fp_index, "%s", index_words[word_count]) != EOF) {
        // 将单词转换为小写字母
        for (int i = 0; index_words[word_count][i]; i++) {
            index_words[word_count][i] = tolower(index_words[word_count][i]);
        }
        word_count++;
    }
    fclose(fp_index);

    // 读取英文文章
    FILE *fp_in = fopen("in.txt", "r");
    if (fp_in == NULL) {
        perror("Error opening in.txt");
        return 1;
    }
    char word[MAX_WORD_LEN];
    char error_words[MAX_WORDS][MAX_WORD_LEN];
    int error_count = 0;
    while (fscanf(fp_in, "%s", word) != EOF) {
        // 将单词转换为小写字母
        for (int i = 0; word[i]; i++) {
            word[i] = tolower(word[i]);
        }
        // 检查单词是否在索引表中
        int found = 0;
        for (int i = 0; i < word_count; i++) {
            if (strcmp(word, index_words[i]) == 0) {
                found = 1;
                break;
            }
        }
        // 若单词不在索引表中,则将其存储到错误单词数组中
        if (!found) {
            strcpy(error_words[error_count], word);
            error_count++;
        }
    }
    fclose(fp_in);

    // 对错误单词数组进行字典序排序
    for (int i = 0; i < error_count - 1; i++) {
        for (int j = i + 1; j < error_count; j++) {
            if (strcmp(error_words[i], error_words[j]) > 0) {
                char temp[MAX_WORD_LEN];
                strcpy(temp, error_words[i]);
                strcpy(error_words[i], error_words[j]);
                strcpy(error_words[j], temp);
            }
        }
    }

    // 将排序后的错误单词输出到error.txt文件中
    FILE *fp_error = fopen("error.txt", "w");
    if (fp_error == NULL) {
        perror("Error opening error.txt");
        return 1;
    }
    for (int i = 0; i < error_count; i++) {
        fprintf(fp_error, "%s\n", error_words[i]);
    }
    fclose(fp_error);

    return 0;
}

注意:

  • 代码中使用了 #define 定义了两个常量:MAX_WORDSMAX_WORD_LEN,分别代表单词索引表中最多包含的单词数和每个单词的最大长度。
  • 代码使用了 fopen() 打开文件,并使用 fscanf() 读取文件内容。
  • 代码使用了 tolower() 将所有单词转换为小写字母。
  • 代码使用了 strcmp() 比较两个字符串。
  • 代码使用了 strcpy() 复制字符串。
  • 代码使用了 fprintf() 将错误单词输出到文件中。

测试用例:

  • index.txt 文件内容:
hello
world

  • in.txt 文件内容:
Hello World!
This is a test.

  • 运行程序后,error.txt 文件内容:
this
is
a
test
C语言实现英文文章单词正确性检查:利用索引表识别错误单词

原文地址: https://www.cveoy.top/t/topic/glYt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录