比较循环中的下一项,连接字符串并保留列表项

Compare next item in loop, concatenate string and keep list items

我下面 defaultdict(list)cols:

defaultdict(<class 'list'>,
{1: [{'text': 'Page',
       'top': Decimal('83.640')
    },{'text': '1,',
       'top': Decimal('83.640')
    },{'text': 'col',
       'top': Decimal('98.040')
    },{'text': '1.',
       'top': Decimal('98.040')
    }],
2: [{'text': 'Page',
    'top': Decimal('112.920')
    },{'text': '1,',
    'top': Decimal('112.920')
    },{'text': 'col',
    'top': Decimal('132.020')
    },{'text': '2.',
    'top': Decimal('132.020')
    }],
3: [{'text': 'Page',
    'top': Decimal('127.560')
    },{'text': '1,',
    'top': Decimal('127.560')
    },{'text': 'col',
    'top': Decimal('167.060')
    },{'text': '3',
    'top': Decimal('167.060')
}]})

我想转换,因此对于 defaultdict(list) 中的每个 col(1、2 和 3),我会连接 text 字符串,如果top 值等于(或在公差范围内)列表中下一个 text 字符串的级别。

如果不是,我想加上代表"a new line"的东西。

因此,例如上面的列表:

[0]:
Page 1,
Col 1.
[1]:
Page 1,
Col 2.
[2]:
Page 1,
Col 3.

到目前为止,这是我的代码:

current_row = [list(cols.values())[0][0], ] #The first word.
row_list = [current_row,]
for col in cols.values():
    for i, word in enumerate(col):
        prevWord = col[i - 1]
        if i > 0:  # skip first word
            if abs(prevWord['bottom'] - word['bottom']) <= float(10): #10 is the tolerance level.
                #distance is small, use same row 
                current_row.append(word)
            else:
                # distance is big, create new row
                current_row = [word, ]
                row_list.append(current_row)

然而,这似乎只是添加了一个包含所有元素的新列表(与我原来的列表相同,没有 1,2,3 键)。

预期输出:

{
    [{'text': 'Page 1,',
      'top': Decimal('83.640')
    },{'text': 'col 1.',
       'top': Decimal('98.040')
    }],
    [{'text': 'Page 1,',
      'top': Decimal('112.920')
    },{'text': 'col 2.',
       'top': Decimal('132.020')
    }],
    [{'text': 'Page 1,',
       'top': Decimal('127.560')
    },{'text': 'col 3.',
       'top': Decimal('167.060')
    }]
}

正如您在上面看到的,如果 top 值在容差范围内并且 top 值保留用于项目,则 text 已连接。

您的代码中的问题是,当差异在容差范围内时,您没有连接字符串;你只是做了一个新项目。试试这个代码:

row_list = []
for col in cols.values():
    current_row = [col[0]]
    for i, word in enumerate(col):
        prevWord = col[i - 1]
        if i > 0:  # skip first word
            if abs(prevWord['top'] - word['top']) <= float(10): #10 is the tolerance level.
                #distance is small, use same row
                current_row[-1]['text'] += " " + word['text']
            else:
                # distance is big, create new row
                current_row.append(word) 
    row_list.append(current_row)
    current_row = []

print(row_list)