【问题标题】:Inverted index given a list of document tokens using python?使用python给定文档标记列表的倒排索引?
【发布时间】:2015-01-19 07:09:22
【问题描述】:

我是 python 的新手。给定文档标记列表,我需要创建一个倒排索引函数。该索引将每个唯一的单词映射到一个文档 ID 列表,按升序排序。

我的代码:

def create_index(tokens):
    inverted_index = {}
    wordCount = {}
    for k, v in tokens.items():
        for word in v.lower().split():
            wordCount[word] = wordCount.get(word,0)+1
            if inverted_index.get(word,False):
                if k not in inverted_index[word]:
                    inverted_index[word].append(k)
            else:
                inverted_index[word] = [k]
    return inverted_index, wordCount

注意:当输入参数的格式为 {1:"Madam I am Adam",2: "I have never been afraid of him"} 时,这可以正常工作

我为上面的例子得到的输出:

{'madam': [1], 'afraid': [2], 'i': [1, 2], 'of': [2], 'never': [2], 'am': [1], 'been': [2], 'adam': [1], 'have': [2], 'him': [2]}

根据我的代码 K,v 对应列表的键和值

当我们使用参数调用 create_index 函数时所需的输出:

index = create_index([['a', 'b'], ['a', 'c']])
>>> sorted(index.keys())
['a', 'b', 'c']
>>> index['a']
[0, 1]
index['b']
[0]
index['c']
[1]

【问题讨论】:

  • [[1:'a', 'b'], [2:'a', 'c']] 不是合法的python。你的意思是某种字典?其次,sorted(index.keys()) 应该失败,因为 create_index 返回一个元组,而不是一个字典,并且元组没有 .keys() 方法。所以,请告诉我们你实际使用的是什么
  • 另外,输出中的 index['c'] 是什么?你没说。
  • @inspectorG4dget sorted 接受任何类型的可迭代;并且该函数应该返回一个字典(一个索引)。
  • @poke: return inverted_index, wordCount .keys 方法
  • @inspectorG4dget desired 输出与 OP 解决此问题的尝试几乎没有关系 :)

标签: python list inverted-index


【解决方案1】:

这样的?

>>> from collections import defaultdict
>>> def create_index (data):
        index = defaultdict(list)
        for i, tokens in enumerate(data):
            for token in tokens:
                index[token].append(i)
        return index

>>> create_index([['a', 'b'], ['a', 'c']])
defaultdict(<class 'list'>, {'b': [0], 'a': [0, 1], 'c': [1]})
>>> index = create_index([['a', 'b'], ['a', 'c']])
>>> index.keys()
dict_keys(['b', 'a', 'c'])
>>> index['a']
[0, 1]
>>> index['b']
[0]

【讨论】:

  • 您的功能有效。但我不想在运行时显式定义索引,因此我在主函数中定义了 index= create_index(data) ..但是通过这样做,函数在测试时不会返回每个元素的索引..当我在控制台中运行以下代码时,会发生以下情况.. create_index([['a', 'b'], ['a', 'c']]) 索引被创建.. 但是当我调用 index[' a'] 它抛出一个异常,指出在运行时未定义 tat 索引..我该如何纠正这个?请帮忙
  • 我不明白你在说什么。 “在运行时明确定义索引”是什么意思?正如您在我的代码中看到的那样,我也这样做了index = create_index(…)。该代码也遵循您想要的行为,所以我不明白您要尝试什么......
  • create_index 返回索引,因此您需要将其存储在某个地方(例如,在变量index 中)。只有这样您才能使用该变量访问索引;否则变量将是未定义的。
猜你喜欢
  • 1970-01-01
  • 2016-07-18
  • 2012-03-16
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多