构建单词字典库(可以下载一些文档,并进行字符串处理,提取其中的 单词,从而构建字典库)。c语言完成
时间: 2023-12-15 10:05:36 浏览: 22
以下是一个简单的 C 语言程序,可以从文本文件中读取单词并构建字典库。程序假设文本文件中每个单词都以空格或换行符分隔,并且单词不包含标点符号或其他特殊字符。在实际使用中,您可能需要根据自己的需求进行修改。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD_LENGTH 100
// 哈希表结构体
typedef struct {
char* key; // 单词
int value; // 出现次数
} KeyValuePair;
typedef struct {
int size;
int count;
KeyValuePair* table;
} HashTable;
// 哈希函数,这里使用简单的除留余数法
int hash(char* key, int size) {
int hash = 0;
while (*key) {
hash = (hash * 31 + *key++) % size;
}
return hash;
}
// 创建哈希表
HashTable* createHashTable(int size) {
HashTable* table = malloc(sizeof(HashTable));
table->size = size;
table->count = 0;
table->table = calloc(size, sizeof(KeyValuePair));
return table;
}
// 销毁哈希表
void destroyHashTable(HashTable* table) {
for (int i = 0; i < table->size; i++) {
free(table->table[i].key);
}
free(table->table);
free(table);
}
// 插入键值对
void insertKeyValuePair(HashTable* table, char* key, int value) {
int index = hash(key, table->size);
while (table->table[index].key != NULL) {
if (strcmp(table->table[index].key, key) == 0) {
table->table[index].value += value;
return;
}
index = (index + 1) % table->size;
}
table->table[index].key = strdup(key);
table->table[index].value = value;
table->count++;
}
// 查找键值对
int findKeyValuePair(HashTable* table, char* key) {
int index = hash(key, table->size);
while (table->table[index].key != NULL) {
if (strcmp(table->table[index].key, key) == 0) {
return table->table[index].value;
}
index = (index + 1) % table->size;
}
return 0;
}
// 从文件中读取单词并插入哈希表
void readWordsFromFile(char* filename, HashTable* table) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Failed to open file: %s\n", filename);
return;
}
char word[MAX_WORD_LENGTH];
while (fscanf(file, "%s", word) != EOF) {
// 将单词转换为小写字母
for (int i = 0; word[i]; i++) {
word[i] = tolower(word[i]);
}
// 插入哈希表
insertKeyValuePair(table, word, 1);
}
fclose(file);
}
int main() {
HashTable* table = createHashTable(1000);
readWordsFromFile("test.txt", table);
printf("Total words: %d\n", table->count);
printf("Occurrences of 'hello': %d\n", findKeyValuePair(table, "hello"));
destroyHashTable(table);
return 0;
}
```
在这个程序中,我们使用了一个简单的哈希表来存储单词和它们出现的次数。哈希表的键是单词本身,值是单词出现的次数。我们还实现了插入键值对、查找键值对、创建哈希表和销毁哈希表等基本操作。
要使用该程序,您需要将要处理的文本文件名作为参数传递给 `readWordsFromFile` 函数,该函数将从文件中读取单词并将它们插入哈希表。在上面的示例中,我们使用了一个名为 `test.txt` 的文件作为示例输入。程序输出哈希表中单词的总数以及特定单词的出现次数。