[英]Python multi level default dict
我正在做倒排索引,為此我從文件中獲取值,文件的每個值都采用以下形式:
document_Id'\\ t'term_Id'\\ t'pos_1'\\ t'pos_2 ...'\\ t'pos_n
這是一個前向索引表示形式。我想將其轉換為倒排索引,看起來像
term_Id'\\ t'“ doc_Id:pos1,pos2 ... posn”“ doc_Id:pos1,pos2 ... posn”
為此,我使用列表類型的默認字典。這是我的功能:
nestedDict = defaultdict(lambda:defaultdict(list))
def getInfo(line):
global nestedDict
tokens = re.split(r'\t+',line)
docInfo = int(tokens[0]) #Set document Id
termId = int(tokens[1]) #Set Term Id
currentPosition = int(tokens[2])
nestedDict[str(termId)][str(docInfo)] = str(currentPosition)
if len(tokens) > 3 :
for i in range(3,len(tokens)):
position = int(tokens[i])-currentPosition
currentPosition = currentPosition + position
nestedDict[str(termId)][str(docInfo)].append(currentPosition)
它給我一個錯誤:Str沒有方法.append。 我是python新手,任何幫助將不勝感激。
您的嵌套defaultdict
使nestedDict[...][...]
成為list
,但隨后您為其分配了一個字符串。 我認為您無論如何都不需要分配:為什么不讓循環處理所有位置呢?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.