Python多级默认di

2024-09-28 05:26:42 发布

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

我在做倒装索引。用于为此,我从一个文件。每个文件的值的格式为:

文档\u Id'\t'术语\u Id'\t'位置\u 1'\t'位置\u 2…'\t'位置\u n

这是一个正向索引表示,我想把它转换成倒排索引

term \u Id'\t'“doc \u Id:pos1,pos2…posn”“doc \u Id:pos1,pos2…posn”

为此,我使用默认的dict of list类型。这个我的职责是:

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有没有方法。追加。 我是新来的Python。有吗我们将不胜感激。你知道吗


Tags: 文件iddoclistinttokensstrpos1
1条回答
网友
1楼 · 发布于 2024-09-28 05:26:42

嵌套的defaultdict使nestedDict[...][...]成为list,但随后为其分配一个字符串。我认为你不需要这个任务:为什么不让循环处理所有的位置呢?你知道吗

相关问题 更多 >

    热门问题