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

2024-05-20 01:06:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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]

Tags: 函数代码in文档列表for参数get
1条回答
网友
1楼 · 发布于 2024-05-20 01:06:28

像这样的?

>>> 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]

相关问题 更多 >