倒排索引是一种信息检索技术,用于快速查找包含特定词汇的文档,在Python中,我们可以使用字典来实现倒排索引,以下是一个简单的示例:

def create_inverted_index(docs):
inverted_index = {}
for doc_id, doc in enumerate(docs):
words = doc.split()
for word in words:
if word not in inverted_index:
inverted_index[word] = []
if doc_id not in inverted_index[word]:
inverted_index[word].append(doc_id)
return inverted_index
示例文档列表
documents = [
"the quick brown fox",
"jumps over the lazy dog",
"fox over jumps"
]
创建倒排索引
inverted_index = create_inverted_index(documents)
输出倒排索引
print(inverted_index) 在这个示例中,我们首先定义了一个名为create_inverted_index的函数,它接受一个文档列表作为输入,我们遍历每个文档,将文档拆分为单词,并将每个单词添加到倒排索引字典中,如果单词不在字典中,我们将其添加到字典中,并将其关联到一个空列表,我们将文档ID添加到与该单词关联的列表中(如果尚未添加),我们返回倒排索引字典。
在主程序中,我们创建了一个示例文档列表,然后调用create_inverted_index函数来创建倒排索引,我们打印出倒排索引的内容。

【版权声明】:本站所有内容均来自网络,若无意侵犯到您的权利,请及时与我们联系将尽快删除相关内容!
发表回复