我想构建一个倒排索引,即将文本映射到它来自的文档。 它在列表/文档中的位置。从列表中创建一个字典
在我来说,我已经解析包含列表清单(即的列表)。
我的输入是这样的。
[
['why', 'was', 'cinderella', 'late', 'for', 'the', 'ball', 'she', 'forgot', 'to', 'swing', 'the', 'bat'],
['why', 'is', 'the', 'little', 'duck', 'always', 'so', 'sad', 'because', 'he', 'always', 'sees', 'a', 'bill', 'in', 'front', 'of', 'his', 'face'],
['what', 'has', 'four', 'legs', 'and', 'goes', 'booo', 'a', 'cow', 'with', 'a', 'cold'],
['what', 'is', 'a', 'caterpillar', 'afraid', 'of', 'a', 'dogerpillar'],
['what', 'did', 'the', 'crop', 'say', 'to', 'the', 'farmer', 'why', 'are', 'you', 'always', 'picking', 'on', 'me']
]
这是我的代码
def create_inverted(mylists):
myDict = {}
for sublist in mylists:
for i in range(len(sublist)):
if sublist[i] in myDict:
myDict[sublist[i]].append(i)
else:
myDict[sublist[i]] = [i]
return myDict
它确实建字典,但是当我做了搜索我没有得到正确的结果 。我正在尝试做这样的事情。
documents = [['owl', 'lion'], ['lion', 'deer'], ['owl', 'leopard']]
index = {'owl': [0, 2],
'lion': [0, 1], # IDs are sorted.
'deer': [1],
'leopard': [2]}
def indexed_search(documents, index, query):
return [documents[doc_id] for doc_id in index[query]]
print indexed_search(documents, index, 'lion')
在哪里我可以输入搜索文本,它会得到列表id。
任何想法。
您是否需要存储每个单词来自哪个文档的信息?您只能存储有关文档中位置的信息。 – user2357112
是的。所以当我搜索我得到那些包含文本列表.http://stackoverflow.com/questions/17554977/inverted-index-in-python-not-returning-desired-results – user3247054