我是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]
答案 0 :(得分:2)
这样的东西?
>>> 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]