首页 > 解决方案 > 动态过滤列表并删除循环中的项目

问题描述

我有以下数据(在我的代码中的列表中表示):

word_list = [{'bottom': Decimal('58.650'),  
  'text': 'Contact'
 },
 {'bottom': Decimal('77.280'),  
  'text': 'email@domain.com'
 },
 {'bottom': Decimal('101.833'),
  'text': 'www.domain.com'
 },
 {'bottom': Decimal('116.233'),
  'text': '(Acme INC)'
 },
 {'bottom': Decimal('74.101'),
  'text': 'Oliver'
 },
 {'bottom': Decimal('90.662'),
  'text': 'CEO'
 }]

以上数据来自PDF文本提取。我正在尝试解析它并根据bottom值保留布局格式。

想法是检查bottom当前单词的值,然后找到所有匹配的单词,即特定范围内,容差为threshold=

这是我的代码:

threshold = float('10')
current_row = [word_list[0], ]
row_list = [current_row, ]

for word in word_list[1:]:

    if abs(current_row[-1]['bottom'] - word['bottom']) <= threshold:
       # 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)

因此,这将返回批准阈值的单词列表。

我有点卡在这里,因为在迭代列表时可能会发生这些单词的bottom值彼此非常接近,因此它将在多次迭代中选择相同的接近单词。

例如,如果一个单词的底部值接近已添加到 的单词row_list,它只会再次将其添加到列表中。

我想知道是否可以删除已经迭代/添加的单词?就像是:


if abs(current_row[-1]['bottom'] - word['bottom']) <= threshold:
   [...]
else:
   [...]

del word from word_list

但是我不确定如何实现这个?因为我无法修改word_list循环内的内容。

标签: pythonpython-3.x

解决方案


您可以指定排序参数,例如

word_list.sort(key=lambda x: x['bottom'])

这导致

word_list.sort(key=lambda x: x['bottom'])
rows = []
current = [word_list.pop(0)]  # reversing the sort and using pop() is more efficient
while word_list:
    if word_list[0]['bottom'] - current[-1]['bottom'] < threshold:
        current.append(word_list.pop(0))
    else:
        rows.append(current)
        current = [word_list.pop(0)]
rows.append(current)

代码迭代word_list直到它为空。当前单词(在位置 0,尽管反转会提高效率)与最后一个有序单词进行比较。最终结果是 ( pprint.pprint(rows)):

[[{'bottom': Decimal('58.650'), 'text': 'Contact'}],
 [{'bottom': Decimal('74.101'), 'text': 'Oliver'},
  {'bottom': Decimal('77.280'), 'text': 'email@domain.com'}],
 [{'bottom': Decimal('90.662'), 'text': 'CEO'}],
 [{'bottom': Decimal('101.833'), 'text': 'www.domain.com'}],
 [{'bottom': Decimal('116.233'), 'text': '(Acme INC)'}]]

推荐阅读