使用python提供文档标记列表的反向索引?

使用python提供文档标记列表的反向索引?,python,list,inverted-index,Python,List,Inverted Index,我是python的新手。我需要创建一个倒排索引函数,给出一个文档标记列表。索引将每个唯一的单词映射到文档ID列表,并按递增顺序排序 我的代码: def create_index(tokens): inverted_index = {} wordCount = {} for k, v in tokens.items(): for word in v.lower().split(): wordCount[word] = wordCoun

我是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从未害怕过他”}时,这可以很好地工作

我从上述示例中获得的输出:

{'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]
像这样的

>>> 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]
>>从集合导入defaultdict
>>>def创建索引(数据):
索引=默认目录(列表)
对于i,枚举中的令牌(数据):
对于令牌中的令牌:
索引[token]。追加(i)
回报指数
>>>创建索引(['a',b',['a',c']]
defaultdict(,{'b':[0],'a':[0,1],'c':[1]})
>>>索引=创建索引(['a',b'],['a',c']])
>>>index.keys()
口述键(['b','a','c'])
>>>索引['a']
[0, 1]
>>>索引['b']
[0]

[[1:'a','b',[2:'a','c']]
不是合法的python。你是说某种字典吗?其次,
sorted(index.keys())
应该失败,因为
create\u index
返回一个元组,而不是dict,并且元组没有
.keys()
方法。那么,请告诉我们您实际使用的是什么,输出中的索引['c']是什么?您没有说。@inspectorG4dget
sorted
接受任何类型的iterable;函数应该返回一个字典(索引)。@poke:
返回反向的索引,wordCount
@inspectorG4dget所需的输出与OP试图解决这个问题几乎没有关系:)您的函数可以工作。但我不想在运行时显式定义索引,因此我在主函数中定义了index=create_index(data)。但通过这样做,函数在测试时不会返回每个元素的索引。当我在控制台中运行以下代码时,会发生以下情况。。创建索引(['a',b'],['a',c']])将创建索引。。但是当我调用index['a']时,它抛出一个异常,声明在运行时没有定义tat索引。我如何纠正这个问题??请帮帮我,我不明白你在说什么。“在运行时明确定义索引”是什么意思?正如您在我的代码中所看到的,我也创建了索引(…)
。代码也遵循您想要的行为,因此我不明白您在尝试什么…
create_index
返回索引,因此您需要将其存储在某个位置(例如,在变量
index
中)。只有这样,您才能使用该变量访问索引;否则该变量将是未定义的。