【问题标题】:Create functions in Python NLTK to get information retrieval在 Python NLTK 中创建函数以获取信息检索
【发布时间】:2018-05-16 20:57:23
【问题描述】:

我是使用Python NLTK创建倒排索引来获取信息检索的初学者。

我成功创建的函数makeInvertedIndex是将一个dict变量rdes_list作为输入,输出是一个倒排索引字典。 例如:

input rdes_list = {1:'hello world',2:'hello',3:'hello cat',4:'hellolot of cats'}

输出 index_dict = {'hello': [0, 1, 2], 'cat': [2], 'of': [3], 'world': [0], 'cats': [3] , 'hellolot': [3]}

基于上面的函数,我遇到了创建另外两个函数的问题: 第一个是创建一个orSearch (invertedIndex, query)函数,它接受一个倒排索引(即index_dict)和查询(即一个单词列表),然后返回一组文档编号指定所有包含查询中任何字词的文档。

第二个是创建一个andSearch(invertedIndex, query)函数,它接受一个倒排索引(即index_dict)和query(即一个单词列表),然后返回集合文档编号指定包含查询中的所有个单词的所有文档。

【问题讨论】:

    标签: python-3.x nltk information-retrieval


    【解决方案1】:

    我提供以下解决方案:

    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}
    

    希望我没有遗漏您的请求。

    【讨论】:

    • 这看起来很有帮助。然而,我们试图鼓励贡献者解释他们的解决方案为什么会起作用,或者它正在解决什么问题。这有助于其他读者从所提供的答案中学习。您可以在帖子中添加一两句话吗?
    • @Elliot。太感谢了。但是,您的代码实际上并不能解决问题。回溯报告的错误说表示键,值的元组没有属性items()。
    • 你用的是什么python版本?
    猜你喜欢
    • 2014-12-21
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多