脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 实现倒排索引的方法

python 实现倒排索引的方法

2021-05-07 00:18涛涛不绝蕾蕾于冬 Python

今天小编就为大家分享一篇python 实现倒排索引的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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
2
3
1 3,4
2 3,4,2,4
3 2

输出:

?
1
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 实现倒排索引的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/xiaoleiniu1314/article/details/80243050

延伸 · 阅读

精彩推荐