简易倒排索引

本文介绍了一种使用C++实现的倒排索引结构,该结构能够从多个文件中提取词汇并建立词汇到文件位置的映射,实现高效的词汇查询功能。文章详细展示了倒排索引的初始化过程,包括读取文件、解析单词和更新索引,以及如何通过查询接口获取特定单词在各文件中的出现频率和位置。
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <unordered_map>
struct word_info {
    size_t frequency = 0;
    std::vector<size_t>pos;
};
class inverted_index_map{
public:
    using file_word_info_map = std::unordered_map<std::string, word_info>;  // key -- file path
    using index_map = std::unordered_map<std::string, file_word_info_map>;  // key -- word
public:
    inverted_index_map() = default;
    inverted_index_map(inverted_index_map &) = delete;
    inverted_index_map & operator = (inverted_index_map &) = delete;
    virtual ~inverted_index_map() = default;
public:
    void init(const std::vector<std::string>&files) {
        size_t pos = 0;
        std::string word;
        std::fstream fin;
        for (auto &filepath : files) {
            fin.open(filepath, std::ios::in);
            if (false == fin.is_open()) {
                std::cerr << filepath << " open failed." << std::endl;
                fin.close();
                continue;
            }
            while (fin >> word) {
                std::cout << "word = " << word << std::endl;
                index_map_[word][filepath].frequency++;
                index_map_[word][filepath].pos.emplace_back(pos++);
            }
            fin.close();
        }
    }
    bool query(std::string &word) {
        auto it = index_map_.find(word);
        if (it == end(index_map_)) {
            return false;
        }
        auto &file_word_info_map_ = it->second;
        for (auto &file_word_info : file_word_info_map_) {
            std::cout << file_word_info.first << std::endl;
            std::cout << file_word_info.second.frequency << std::endl;
            for (auto &pos : file_word_info.second.pos) {
                std::cout << pos << std::endl;
            }
            std::cout << file_word_info.second.frequency << std::endl;
        }
        return true;
    }
private:
    index_map index_map_;
};
int main() {
    std::vector<std::string>files{"./test.cpp"};
    inverted_index_map mm;
    mm.init(files);
    std::string word = "return";
    std::cout << mm.query(word) << std::endl;

    return 0;
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值