我有一个如下列表:
word_list = '''
[{'bottom': Decimal('58.650'),
'text': 'Welcome'
{'bottom': Decimal('74.101'),
'text': 'This'
},
{'bottom': Decimal('74.101'),
'text': 'is'
},
{'bottom': Decimal('77.280'),
'text': 'Oliver'
}]
'''
表示一系列单词:Contact Name is Oliver,它是从 PDF 文件中提取的。该bottom值是从底部到页面顶部的距离。
该列表bottom按键排序:
words = sorted(word_list, key=itemgetter('bottom'))
我正在尝试迭代列表和每个单词以查看该单词是否属于同一行 - 或者它应该附加到新行。
我想这样做的方法是比较bottom每个循环中的值,公差为xx. 例如,This is OliverPDF 文件中的所有单词都在同一行 - 但底部值不相等(因此是公差级别)。
预期产出
我试图最终得到的结果是:
[{'text': 'Welcome',
'line:' 1
{'text': 'This is Oliver',
'line': 2
}]
这是我到目前为止所拥有的:
for i, word in enumerate(word_list):
previous_element = word_list[i-1] if i > 0 else None
current_element = word
next_element = word_list[i +1] if i < len(word_list) - 1 else None
if math.isclose(current_element['bottom'], next_element['bottom'], abs_tol=5):
# Append the word to the line
我有点卡在上面的循环中。我似乎无法弄清楚这math.isclose()是否正确以及如何实际附加 theline[i]和实际单词以创建一个行句。