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设计】。

相关文章

python3使用flask编写注册post接口的方法

使用python3的Flask库写了一个接口,封装了很多东西,仅供参考即可! 代码如下: #!/usr/bin/python3 # -*- coding: utf-8 -*- im...

Python中的pygal安装和绘制直方图代码分享

Python中的pygal安装和绘制直方图代码分享

有关pygal的安装,大家可以参阅《pip和pygal的安装实例教程》。 直方图: 直方图是一个特殊的条,它可以取3个数值:纵坐标高度,横坐标开始和横坐标结束。 import pyg...

python定位xpath 节点位置的方法

chrome 右键有copy xpath地址 但是有些时候获取的可能不对 可以自己用代码验证一下 如果还是不行 可以考虑从源码当中取出来 趁热打铁,使用前一篇文章中 XPath 节点来定...

python 排列组合之itertools

python 2.6 引入了itertools模块,使得排列组合的实现非常简单:复制代码 代码如下:import itertools  有序排列:e.g., 4个数内选2个排列...

基于python 字符编码的理解

一、字符编码简史: 美国:1963年 ASCII (包含127个字符  占1个字节) 中国:1980年 GB2312 (收录7445个汉字,包括6763个汉字和682个其它符号...