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]}

相关推荐