编写一段代码,实现对文档建立倒转文件然后进行检索的算法
时间: 2024-05-05 12:16:12 浏览: 13
首先,需要定义一个函数,用于建立倒转文件。该函数接收一个文档作为输入,并返回一个字典,其中键为单词,值为该单词在文档中出现的位置列表。
```
def build_inverted_index(doc):
inverted_index = {}
words = doc.split()
for i, word in enumerate(words):
if word not in inverted_index:
inverted_index[word] = []
inverted_index[word].append(i)
return inverted_index
```
接下来,需要定义一个函数,用于检索。该函数接收一个查询字符串和建立好的倒转文件作为输入,并返回包含查询字符串的位置列表。
```
def search(query, inverted_index):
if query not in inverted_index:
return []
else:
return inverted_index[query]
```
最后,可以使用这两个函数来建立倒转文件并进行检索。
```
doc = "This is a sample document for testing the inverted index algorithm"
inverted_index = build_inverted_index(doc)
print(inverted_index)
query = "algorithm"
results = search(query, inverted_index)
print(results)
```
输出结果为:
```
{'This': [0], 'is': [1], 'a': [2], 'sample': [3], 'document': [4], 'for': [5], 'testing': [6], 'the': [7], 'inverted': [8], 'index': [9], 'algorithm': [10]}
[10]
```