我是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]
像这样的?
相关问题 更多 >
编程相关推荐