python 实现倒排索引的方法
代码如下:
#encoding:utf-8 fin = open('1.txt', 'r') ''' 建立正向索引: “文档1”的ID > 单词1:出现位置列表;单词2:出现位置列表;………… “文档2”的ID > 此文档出现的关键词列表。 ''' forward_index = {} for line in fin: line = line.strip().split() forward_index[int(line[0])] = {} words = line[1].split(',') for i, index in enumerate(words): if int(index) not in forward_index[int(line[0])].keys(): forward_index[int(line[0])][int(index)] = [i] else: forward_index[int(line[0])][int(index)].append(i) print 'forward_index:', forward_index ''' 建立倒排索引: “关键词1”:“文档1”的ID,“文档2”的ID,………… “关键词2”:带有此关键词的文档ID列表。 ''' inverted_index = {} for doc_id, words in forward_index.items(): for word_id in words.keys(): if word_id not in inverted_index.keys(): inverted_index[word_id] = [doc_id] elif doc_id not in inverted_index[word_id]: inverted_index[word_id].append(doc_id) print 'inverted_index:', inverted_index
输入(文档id:单词id):
1 3,4 2 3,4,2,4 3 2
输出:
forward_index: {1: {3: [0], 4: [1]}, 2: {2: [2], 3: [0], 4: [1, 3]}, 3: {2: [0]}} inverted_index: {2: [2, 3], 3: [1, 2], 4: [1, 2]}
相关推荐
章鱼之家 2020-06-08
sifeimeng 2020-05-29
PasserbyX 2020-05-16
mengyue 2020-04-17
qiburen 2020-03-20
lixiaotao 2020-03-05
yanweiqi 2020-03-03
sifeimeng 2020-01-23
tigercn 2019-12-30
xiaoxiaoabc 2014-06-27
devefx 2019-07-30
冬冬阳光 2017-12-25
唐爱平的blog 2011-10-13
greatking 2011-09-27
某某某 2014-06-27
AFei00 2019-06-28
喜糖 2010-11-22
hankesi000 2019-06-25
chenhua 2019-06-20