C语言实现英文文章单词正确性检查

本程序使用C语言实现英文文章单词正确性检查功能,通过读取单词索引表文件,判断文章中的单词是否在索引表中,并将错误单词输出到指定文件。

思路:

  1. 读取单词索引表,将所有单词存储到一个数组中。
  2. 读取英文文章,逐个单词进行检查,如果不在单词索引表中,则将其转换为小写并存储到一个错误单词数组中。
  3. 对错误单词数组进行排序,然后输出到error.txt文件中。

代码如下:

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

#define MAX_WORDS 1000
#define MAX_WORD_LEN 50

int main() {
    char index_filename[] = "index.txt";
    char in_filename[] = "in.txt";
    char error_filename[] = "error.txt";

    // 存储单词索引表
    char words[MAX_WORDS][MAX_WORD_LEN];
    int word_count = 0;

    // 存储错误单词
    char error_words[MAX_WORDS][MAX_WORD_LEN];
    int error_word_count = 0;

    // 读取单词索引表
    FILE *fp = fopen(index_filename, "r");
    if (fp == NULL) {
        perror("fopen index.txt");
        return 1;
    }
    while (fscanf(fp, "%s", words[word_count]) != EOF) {
        word_count++;
    }
    fclose(fp);

    // 读取英文文章
    fp = fopen(in_filename, "r");
    if (fp == NULL) {
        perror("fopen in.txt");
        return 1;
    }
    char word[MAX_WORD_LEN];
    while (fscanf(fp, "%s", word) != EOF) {
        // 检查单词是否在索引表中
        int found = 0;
        for (int i = 0; i < word_count; i++) {
            if (strcasecmp(word, words[i]) == 0) {
                found = 1;
                break;
            }
        }
        // 如果不在索引表中,则将其转换为小写并存储到错误单词数组中
        if (!found) {
            for (int i = 0; word[i]; i++) {
                word[i] = tolower(word[i]);
            }
            strcpy(error_words[error_word_count], word);
            error_word_count++;
        }
    }
    fclose(fp);

    // 对错误单词数组进行排序
    for (int i = 0; i < error_word_count - 1; i++) {
        for (int j = i + 1; j < error_word_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文件中
    fp = fopen(error_filename, "w");
    if (fp == NULL) {
        perror("fopen error.txt");
        return 1;
    }
    for (int i = 0; i < error_word_count; i++) {
        fprintf(fp, "%s\n", error_words[i]);
    }
    fclose(fp);

    return 0;
}

说明:

  • 程序使用strcasecmp函数进行大小写无关的字符串比较。
  • 程序使用tolower函数将单词转换为小写。
  • 程序使用strcpy函数复制字符串。
  • 程序使用strcmp函数进行字符串比较,对错误单词数组进行排序。
  • 程序使用fprintf函数将错误单词输出到error.txt文件中。

测试方法:

  1. 将程序保存为check_words.c文件。
  2. 编译程序:gcc check_words.c -o check_words
  3. 运行程序:./check_words

注意:

  • 程序假设index.txt和in.txt文件位于当前目录下。
  • 程序假设index.txt中的单词个数不超过1000个,每个单词的长度不超过50个字母。
  • 程序假设in.txt中的文章有可能没有经过排版,格式有可能杂乱无章,也有可能没有写完整。
  • 若出错的单词多次出现,则多次输出。
  • 若没有出现错误单词,则什么也不输出。

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

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