python - 动态过滤列表并删除循环中的项目
问题描述
我有以下数据(在我的代码中的列表中表示):
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
循环内的内容。
解决方案
您可以指定排序参数,例如
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)'}]]
推荐阅读
- python - 子集 pandas DataFrame 并拆分为 3 个 DataFrame
- c# - 等待用户使用 Rg.Plugins.Popup 点击弹出窗口
- javascript - 使用 Google Apps 脚本将人员分组的最佳方法
- android - JUnit 5 - 参数化嵌套测试
- javascript - 如何在正则表达式中替换捕获组而不是完整匹配?
- amazon-web-services - 扩展 ECS 集群中的一些(但不是全部)任务
- amazon-s3 - 使用 fetch 调用具有自定义域和签名 cookie 的 Cloudfront S3 端点时出现 403 错误
- python - 在 Python 中获取客户端配置文件 Azure 的访问令牌
- reactjs - 推送状态而不重新触发组件加载
- android - 在其他小部件上颤动阴影