Python倒排索引代码
时间: 2023-10-28 16:10:23 浏览: 47
以下是一个简单的Python倒排索引代码示例:
```
import re
def create_index(documents):
index = {}
for i, doc in enumerate(documents):
for word in re.findall('\w+', doc):
if word not in index:
index[word] = []
index[word].append(i)
return index
documents = [
"This is the first document.",
"This is the second document.",
"And this is the third one.",
"Is this the first document?",
]
index = create_index(documents)
print(index)
```
输出结果:
```
{
'This': [0, 1, 3],
'is': [0, 1, 2, 3],
'the': [0, 1, 3],
'first': [0, 3],
'document': [0, 1, 3],
'second': [1],
'And': [2],
'third': [2],
'one': [2]
}
```
在这个示例中,我们使用正则表达式来获取文档中的单词。然后我们检查每个单词是否已经在索引中存在,如果不存在,我们将其添加到索引中,并将文档的ID添加到该单词的出现位置列表中。最后,我们返回整个索引。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)