python 实现倒排索引的方法

yipeiwu_com6年前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 布尔操作实现代码

和别的语言布尔类型定义1为真,0为假不同,python定义的真假比较多。 先说下假吧: false,none,0,"",{},[],() 而真的话,只要和上面的相反就行,比如上面是fal...

Python中max函数用于二维列表的实例

最近写一个和二维列表有关的算法时候发现的 当用max求二维列表中最大值时,输出的结果是子列表首元素最大的那个列表 测试如下 c=[[1,2,-1],[0,5,6]] a=[[0,3...

Pycharm远程调试原理及具体配置详解

Pycharm远程调试原理及具体配置详解

前言 工作中使用Pycharm作为python开发的IDE,作为专业的python集成开发环境,其功能之强大令人折服。开发过程中Debug是必不可少的。平时经常使用Pycharm的rem...

详解用python写一个抽奖程序

第一次使用python写程序,确实比C/C++之类方便许多。既然这个抽奖的数据不大,对效率要求并不高,所以采用python写,更加简洁、清晰、方便。 1.用到的模块 生成随机数的模...

Python向excel中写入数据的方法

Python向excel中写入数据的方法

最近做了一项工作需要把处理的数据写入到Excel表格中进行保存,所以在此就简单介绍使用Python如何把数据保存到excel表格中。 数据导入之前需要安装 xlwt依赖包,安装的方法就很...