#encoding:utf-8fin = 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