def inverted_index(docs): index = {} for i, doc in enumerate(docs): for word in doc.split(): if word not in index: index[word] = set() index[word].add(i) return index # 读取文档集合 docs = [] with open("docs.txt", "r", encoding='utf-8') as f: for line in f: docs.append(line.strip()) # 输出倒排索引 index = inverted_index(docs) for word in sorted(index): print(word + ":", sorted(index[word]))优化一下这段代码
时间: 2024-01-25 12:03:00 浏览: 76
这段代码实现的是一个简单的倒排索引,对于小规模的文本集合来说已经足够。但对于大规模的文本集合,可以进行以下优化:
1. 使用Python的 `defaultdict` 类型代替普通的字典类型,避免了每次查询时需要判断键是否存在的开销,提高了索引构建的效率。
2. 为了避免在内存中存储过多的文档ID,可以使用一些压缩技术,如变长编码、前缀编码等,将文档ID列表压缩为一个连续的二进制串。
3. 对于一些常见的停用词,可以在构建索引前进行过滤,避免将这些无意义的单词也加入到索引中,浪费存储空间和查询时间。
优化后的代码如下所示:
```
from collections import defaultdict
def inverted_index(docs):
index = defaultdict(list)
for i, doc in enumerate(docs):
for word in doc.split():
index[word].append(i)
return index
# 读取文档集合
docs = []
with open("docs.txt", "r", encoding='utf-8') as f:
for line in f:
docs.append(line.strip())
# 输出倒排索引
index = inverted_index(docs)
for word in sorted(index):
print(word + ":", index[word])
```
在优化后的代码中,使用了 Python 的 `defaultdict` 类型,代替了原来的普通字典类型,避免了判断键是否存在的开销。另外,对于每个单词,使用 `list` 类型存储文档ID列表,避免了使用 `set` 类型存储文档ID的开销,同时也方便了后续的压缩操作。最后,使用 Python 内置的 `sorted` 函数按字典序排序输出结果。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![](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)