说明
获取原始数据并构建倒排索引后,可根据用户输入查找相关内容。
1、先对用户的输入进行分词。
2、然后根据倒排索引获取与每个单词相关的文章。
3、最后,计算每个单词和相关文章之间的分数。分数越高,相关性越大。
实例
def search(self, query): BM25_scores = {} # 对用户输入分词 # 并将其变成 {word: frequency, ...} 的形式 query = jieba.lcut_for_search(query) word2freq = self.format(query) # 遍历每个词 # 计算每个词与相关文章之间的得分(计算公式参考 BM25 算法) for word in word2freq: data = self.iindex.get(word) if not data: continue BM25_score = 0 qf = word2freq[word] df = data['df'] ds = data['ds'] W = math.log((self.N - df + 0.5) / (df + 0.5)) for doc in ds: doc_id = doc['id'] tf = doc['tf'] dl = doc['dl'] K = self.k1 * (1 - self.b + self.b * (dl / self.AVGDL)) R = (tf * (self.k1 + 1) / (tf + K)) * (qf * (self.k2 + 1) / (qf + self.k2)) BM25_score = W * R BM25_scores[doc_id] = BM25_scores[doc_id] + BM25_score if doc_id in BM25_scores else BM25_score # 对所有得分按从大到小的顺序排列,返回结果 BM25_scores = sorted(BM25_scores.items(), key = lambda item: item[1]) BM25_scores.reverse() return BM25_scores
本文链接:http://so.lmcjl.com/news/8828/