c - 阅读 dict 文件找到 "words"并添加到 trie 中

标签 c trie getc

这道题我要通读a,分清什么是单词。一个词不需要有意义,即。单词可以是 asdas、sdgsgd、dog、sweet 等...要访问我必须通过映射文件来完成。

File *map, *dictfile, *datafile;
char *dictname, *dataname;
map = fopen(argv[1],"r");
while (fgets(buffer,sizeof(buffer),map) != NULL)
{
dictname = strtok(buffer," ");
dataname = strtok(NULL, " ");
strtok(dictname,"\n");
strtok(dataname,"\n");

该代码进入映射文件,然后区分文件名和文件名。 从他们那里我打开文件

if((datafile = fopen(dictname,"r")) == NULL) //error checking
{
  in here I have to call a readDict(dictfile)
}

我的问题是在 readDict 中,我必须在这个字典文件中逐个字符地去区分什么是一个词,什么不是。一个词可以由任何字母字符组成。 假设包含:dictionary$@#$LoL!@#FFDAfg(()) 这里面的单词是:dictionary, LoL, FFDAfg。 我需要通读这些字符,如果它是一个字母,我需要直接将它添加到 trie 中(我还没有想出如何通过一次只添加一个字符来管理 trie)或者我必须跟踪每个字符并将其放入一个字符串中,一旦我遇到一个非字母字符,我需要将该“单词”添加到 trie 中。

我的 trie 结构是:

struct trieNode
{
bool isWord;
struct trieNode *children[26]; //26 given there are 26 letters in the alphabet
};

我有方法

struct trieNode *createNode()
{
int i;
struct trieNode *tmp = (struct trieNode*)malloc(sizeof(struct trieNode));
for (i = 0; i<26;i++)
tmp -> children[i] = NULL;

tmp -> isWord = false;
return tmp;

我目前的插入方法是:

void insert(char *key)
{
int level = 0;
int index = getIndex(key[level]); //previously defined just gets the index of where the key should go
int len = strlen(key);

if(root == NULL)
root = createNode(); //root is defined under my struct def as: struct trieNode *root = NULL;
struct trieNode *tmp = root;
for (level = 0; level < len; level++)
{
if (tmp -> children [index] == NULL)
tmp ->children[index] = createNode();

tmp = tmp->children[index];
}
}

我相信如果我最终将一个字符串插入到一个 trie 中,这个方法会起作用,但我的问题是我不确定如何从我之前的 readDict 文件中获取一个字符串。此外,我不确定如何修改它(如果可能)以一次插入一个字符,这样我就可以按字符读取我的字符,然后检查它是否是一个字母并转换为小写字母如果不是,则添加到 trie 中那里。

最佳答案

所以一种粗略的方法是这样的。您可能需要添加更多条件来处理一些边缘情况。

void *readDict(char *fileName)
{
    FILE *file = fopen(fileName, "r");
    char *word = malloc(100);
    int index = 0;
    int c;
    while ((c = fgetc(file)) != EOF)
    {
       char ch = (char)c;
       if (isalpha(ch)) // check if ch is a letter
          word[index++] = ch;
       else
       {
          word[index] = '\0';
          index = 0;
          insert(word);
       }
    }
    fclose(file);
}

关于c - 阅读 dict 文件找到 "words"并添加到 trie 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33252092/

相关文章:

c - 当添加一个整数时,仅记录第一个数字

c++ - c/c++中void指针的使用

big-o - 关于try和基数排序的效率

c - 如何从txt文件C制作数组

c - Linux 中的 getch() 和 getche() 等价于什么?

c - 在 MacOS 上构建 mongodb C 驱动程序

c++ - stdout 除了控制台窗口之外还有其他东西吗?

c - 使用trie的Load的Pset5实现

c - 将递归函数中的几个字符串存储到 struct c

perl - IO::获取和取消获取 unicode 字符的句柄