2015-10-21 37 views
2

對於這個問題,我必須通讀一個並區分一個單詞是什麼。一個詞不需要有意義,即。一個詞可以是asdas,sdgsgd,dog,sweet等等。要訪問我必須通過映射文件來完成。通過一個字典文件找到「單詞」並添加到trie

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,我有性格在這個字典文件去字符來區分究竟是怎樣一個詞,什麼心不是。一個詞可以由任何字母字符組成。 可以說包含:字典$ @#$ LoL!@#FFDAfg(()) 這裏的單詞是:dictionary,LoL,FFDAfg。 我需要閱讀這些字符,如果它是一個字母,我需要直接將其添加到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文件中獲取字符串。此外,我不知道如何修改此(如果可能)一次插入一個字符,所以我可以通過char讀取我的字符,並在我檢查它是否是一個字母,並轉換爲小寫添加到trie,如果它不是那裏。

+0

所以,澄清:你想從你的readDict文件的字符串列表? – rohit89

+0

好吧,我需要閱讀字典文件,並解釋什麼應該被視爲一個「單詞」和什麼不應該,但一旦我找出什麼是一個字,我必須弄清楚如何我可以將它插入到trie @ rohit89 – bkennedy

回答

1

所以一個粗略的做法就是這樣。您可能需要添加一些條件來處理一些邊緣情況。

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); 
} 
+1

我相信你的意思是讓它說void void readDict正確嗎?因爲你沒有在這裏返回任何東西 – bkennedy

+0

是的。固定。謝謝 – rohit89