代码实现输入:一个文档集合,输出:该文档集合的倒排索引
时间: 2023-12-10 17:37:05 浏览: 30
以下是 Python 代码实现:
```python
def inverted_index(documents):
"""
:param documents: list of strings (文档集合)
:return: dict (倒排索引)
"""
inverted_index = {}
for i, doc in enumerate(documents):
for word in doc.split():
if word in inverted_index:
if i not in inverted_index[word]:
inverted_index[word].append(i)
else:
inverted_index[word] = [i]
return inverted_index
```
其中,`inverted_index` 是一个字典,键为单词,值为包含该单词的文档在文档集合中的下标的列表。函数遍历文档集合,对于每个文档,遍历其中的每个单词,将单词作为键,将文档下标添加到值对应的列表中。最终返回倒排索引。
示例输入:
```python
documents = [
'Python is a popular programming language',
'It is also used for data analysis',
'Python is easy to learn'
]
```
示例输出:
```
{
'Python': [0, 2],
'is': [0, 1, 2],
'a': [0],
'popular': [0],
'programming': [0],
'language': [0],
'It': [1],
'also': [1],
'used': [1],
'for': [1],
'data': [1],
'analysis': [1],
'easy': [2],
'to': [2],
'learn': [2]
}
```