簡體   English   中英

根據查詢將字典值的出現次數計算為嵌套列表

[英]Count number of occurrences of dictionary values as nested list based on a query

我建立了這個倒排索引:

{
    'experiment': {'d1': [1, [0]], ..., 'd30': [2, [12, 40]], ..., 'd123': [3, [11, 45, 67]], ...}, 

    'studi': {'d1': [1, [1]], 'd2': [2, [0, 36]], ..., 'd207': [3, [19, 44, 59]], ...}

}

例如,術語experiment在文檔 1 中出現一次,索引為 0,在文檔 30 中出現兩次,索引為 12 和 40,等等。我想知道如何根據字典計算字典中每個術語的出現次數看起來像這樣的查詢:

{
    'q1'  : ['similar', 'law', ..., 'speed', 'aircraft'],
    'q2'  : ['structur', 'aeroelast', ..., 'speed', 'aircraft'], 
    ...
    'q225': ['design', 'factor', ..., 'number', '5']
}

所需的 output 看起來像這樣:

{
    'q1'  : ['d51', 'd874', ..., 'd717'], 
    'q2'  : ['d51', 'd1147', ..., 'd14'],
    ...,
    'q225': ['d1313', 'd996', ..., 'd193']
}

使用代表查詢的鍵和代表查詢出現的文檔的值,列表將按總詞頻的降序排序

Map 查詢文檔向量

文檔向量是帶有項目(document, word_count)的字典。 這些向量可以通過將匹配文檔鍵的字數與默認 word_count 為 0 相加來相加。

將索引轉換為文檔向量

full_index = {
    'experiment': {'d1': [1, [0]],  'd30': [2, [12, 40]],  'd123': [3, [11, 45, 67]] } ,
    'study': {'d1': [1, [1]], 'd2': [2, [0, 36]],  'd207': [3, [19, 44, 59]]}
}

def count_only(docs):
    return {d: occurences[0] for d, occurences in docs.items()}

doc_vector_index = {w: count_only(docs) for w, docs in full_index.items()}

MAP 查詢詞列表到文檔向量列表

for q, words in queries.items():
    vectors = [doc_vector_index[word] for word in words if word in doc_vector_index.keys()]

對文檔向量求和並排序

def doc_vector_add(ldoc, rdoc):
    res = ldoc.copy()
    for doc, count in rdoc.items():
        res[doc] = ldoc.get(doc,0) + count
    return res

for q, words in queries.items():
    vectors = [doc_vector_index[word] for word in words if word in doc_vector_index.keys()]
    total_vector = dict(sorted(functools.reduce(doc_vector_add, vectors, {}).items(), 
        key=lambda item: item[1], 
        reverse=True))
    output[q] = list(total_vector.keys())

使用 reduce functools.reduce(doc_vector_add, vectors, {})處理文檔向量的總和。 這會生成文檔向量,它是查詢中每個單詞的各個向量的總和。 sorted用於對向量的鍵進行排序。

限於前 N 個文件

max_doc_limit = 10
output[q] = list(total_vector.keys())[:max_doc_limit]

在分配給 output 之前,可以通過切片來限制文檔。

ORDER BY COUNT DESC, DOC_ID ASC

sorted(...,key=lambda item: (item[1], -1*int(item[0][1:]),...)

我們可以通過更改傳遞給sorted的鍵 function 來更改 output 的排序順序。 我們使用將元組中的第二個元素乘以 -1 的技巧來反轉從降序到升序的順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM