python代码倒排索引
时间: 2023-09-11 10:09:48 浏览: 152
以下是一个简单的 Python 代码实现倒排索引的示例:
```python
# 定义一个文档列表
docs = [
"The quick brown fox jumps over the lazy dog",
"The lazy dog sleeps over the verandah",
"The quick brown fox jumps over the quick dog",
"The brown dog is quick and the brown fox is lazy",
"The lazy brown dog is quick to jump over the brown fox"
]
# 定义一个空字典,用于存储倒排索引
inverted_index = {}
# 遍历每个文档
for i, doc in enumerate(docs):
# 将文档转换为单词列表
words = doc.lower().split()
# 遍历每个单词
for word in words:
# 如果单词不在倒排索引中,就添加一个新的条目
if word not in inverted_index:
inverted_index[word] = []
# 将文档的编号添加到单词的列表中
inverted_index[word].append(i)
# 打印倒排索引
for word, docs in inverted_index.items():
print(word, ": ", docs)
```
输出结果:
```
the : [0, 1, 2, 3, 4]
quick : [0, 2, 3, 4]
brown : [0, 2, 3, 4]
fox : [0, 2]
jumps : [0, 2]
over : [0, 1, 2, 4]
lazy : [0, 1, 3, 4]
dog : [0, 1, 3, 4]
sleeps : [1]
verandah : [1]
is : [3, 4]
and : [3]
to : [4]
jump : [4]
```
阅读全文