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对象与引用的介绍

Python对象与引用的介绍

对象 Python 中,一切皆对象。每个对象由:标识(identity)、类型(type)、value(值)组成。 1. 标识用于唯一标识对象,通常对应于对象在计算机内存地址。使用...

python互斥锁、加锁、同步机制、异步通信知识总结

某个线程要共享数据时,先将其锁定,此时资源的状态为“锁定”,其他线程不能更改;直到该线程释放资源,将资源的状态变成“非锁定”,其他的线程才能再次锁定该资源。互斥锁保证了每次只有一个线程进...

Python实现计算文件夹下.h和.cpp文件的总行数

平时自己写了很多代码,但从没好好计算总共写了多少行,面试时被问起来,就傻了。。。闲来无事,写个python程序来统计下 import os ###################...

Python字典对象实现原理详解

Python字典对象实现原理详解

字典类型是Python中最常用的数据类型之一,它是一个键值对的集合,字典通过键来索引,关联到相对的值,理论上它的查询复杂度是 O(1) : >>> d = {'a'...

python matplotlib中的subplot函数使用详解

python matplotlib中的subplot函数使用详解

python里面的matplotlib.pylot是大家比较常用的,功能也还不错的一个包。基本框架比较简单,但是做一个功能完善且比较好看整洁的图,免不了要网上查找一些函数。于是,为了节省...