倒排索引C++實現
阿新 • • 發佈:2019-01-06
倒排索引原理:根據屬性的值來查詢記錄位置。
假設有3篇文章,file1, file2, file3,檔案內容如下:
file1 (單詞1,單詞2,單詞3,單詞4....)
file2 (單詞a,單詞b,單詞c,單詞d....)
單詞1 (file1,file3)
單詞2 (file1)
單詞3 (file1,file3)
單詞a (file2, file3)
假設有3篇文章,file1, file2, file3,檔案內容如下:
file1 (單詞1,單詞2,單詞3,單詞4....)
file2 (單詞a,單詞b,單詞c,單詞d....)
file3 (單詞1,單詞a,單詞3,單詞d....)
那麼建立的倒排索引就是這個樣子:單詞1 (file1,file3)
單詞2 (file1)
單詞3 (file1,file3)
單詞a (file2, file3)
...
下面是我對於倒排索引的一個簡單的實現。該程式實現了某目錄下的檔案單詞統計,並建立了倒排索引。
標頭檔案:inverted_index.h
#define MAXLINE 1024 class InvertedIndex { public: InvertedIndex(){} ~InvertedIndex(){result_index_.clear();} int StatWords(const char* file_name); map<string,map<string,int> > result_index(){return result_index_;} private: //存放倒排索引結果,key是單詞,value也是map,該map的key是檔名,value是該單詞在該檔案中出現的次數 map<string,map<string,int> > result_index_; int ParseWordsByLine(char* str_line, const char* file_name); void InsertWordToMap(char* word, const char* file_name); };
實現檔案:inverted_index.cpp
執行結果:int InvertedIndex::StatWords(const char* file_name) { FILE *fp; if((fp = fopen(file_name,"r")) == NULL) { printf("cannot open %s", file_name); return -1; } char str_line[MAXLINE]; while(fgets(str_line, MAXLINE, fp) != NULL) { int len = strlen(str_line); str_line[len-1] = '\0'; /*去掉換行符*/ ParseWordsByLine(str_line,file_name); } fclose(fp); return 0; } int InvertedIndex::ParseWordsByLine(char* str_line, const char* file_name) { if(strlen(str_line) == 0) { return -1; } const char* needle=" \n\t"; /*strtok在s中查詢包含在delim中的字元並用NULL(‘\0’)來替換,直到找遍整個字串。 返回值:從s開頭開始的一個個被分割的串。當沒有被分割的串時則返回NULL。*/ char* word = strtok(str_line, needle); while(word != NULL) { InsertWordToMap(word,file_name); word = strtok(NULL, needle); } return 0; } void InvertedIndex::InsertWordToMap(char* word, const char* file_name) { if(strlen(word) == 0) { return; } string word_str = word; string file_name_str = file_name; map<string,map<string,int> >::iterator it; it = result_index_.find(word_str); if(it == result_index_.end())//not found { map<string,int> file_word_count; file_word_count.insert(pair<string,int>(file_name_str,1)); result_index_[word_str] = file_word_count; } else { map<string,int> file_word_count = result_index_[word_str]; file_word_count[file_name_str] ++ ; result_index_[word_str] = file_word_count; } }