我是初学者,使用Python NLTK创建反向索引以获取信息。
我成功创建的函数 makeInvertedIndex 是将dict变量rdes_list作为输入,输出是反向索引字典。 例如:
输入rdes_list = {1:' hello world',2:' hello',3:' hello cat',4:' hellolot of猫'}
输出index_dict = {'你好':[0,1,2],' cat':[2],'':[3], '世界':[0],'猫':[3],' hellolot':[3]}
基于以上功能,我遇到了创建其他两个功能的问题: 第一个是创建 orSearch (invertedIndex,query)函数,它接受反向索引(即index_dict)和查询(即单词列表),然后返回文档编号集指定包含任何查询中的单词的所有文档。
第二个是创建和Search (invertedIndex,query)函数,它接受反向索引(即index_dict)和查询(即单词列表),然后返回集合文档编号,指定查询中包含所有单词的所有文档。
答案 0 :(得分:0)
我提供以下解决方案:
output_index_dict = {'hello': [0, 1, 2], 'cat': [2], 'of': [3], 'world': [0], 'cats': [3], 'hellolot': [3]}
def orSearch (invertedIndex, query):
result = []
for key, value in invertedIndex.items():
if key in query:
result.append(value)
relevant_documents = [index for indexes in result for index in indexes]
return set(relevant_documents)
>>> orSearch(output_index_dict, ['of', 'hello', 'cat'])
output : {0, 1, 2, 3}
def andSearch (invertedIndex, query):
result = []
for key, value in invertedIndex.items():
if key in query:
result.append(value)
common_indexes = set.intersection(*map(set,result))
return common_indexes
>>> andSearch(output_index_dict, ['hellolot', 'of', 'cats'])
output : {3}
希望我的请求中没有遗漏任何内容。