python 实现倒排索引的方法

yipeiwu_com5年前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]}

以上这篇python 实现倒排索引的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 读取excel文件生成sql文件实例详解

python 读取excel文件生成sql文件实例详解 学了python这么久,总算是在工作中用到一次。这次是为了从excel文件中读取数据然后写入到数据库中。这个逻辑用java来写的话...

matplotlib实现热成像图colorbar和极坐标图的方法

matplotlib实现热成像图colorbar和极坐标图的方法

热成像图 %matplotlib inline from matplotlib import pyplot as plt import numpy as np def f(x,...

在Python中操作日期和时间之gmtime()方法的使用

 gmtime()方法转换历元到一struct_time以UTC其中dst的标志值始终为0以秒表示时间。如果不设置秒时或None,返回的时间为当前time()。 语法 以下是g...

Win8下python3.5.1安装教程

Win8下python3.5.1安装教程

本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下 首先,找到python下载的地址,如下图所示 在这里我选择了python 3.5.1(看网上的其...

numpy按列连接两个维数不同的数组方式

合并两个维数不同的ndarray 假设我们有一个3×2 numpy数组: x = array(([[1,2], [3, 4], [5,6]])) 现在需要把它与一个一维数组:...