请考虑以下列表:
column = list()
我有一个 Python 脚本,它迭代一个 PDF 文件,将每个页面转换为一个图像,然后对于每个页面,我根据我定义的"列"进一步裁剪它。对于每个裁剪的部分,我使用 OCR(tesseract(输出文本内容。
我的PDF文件有两页长,这是内容:
#Page 1
Page 1 - Col 1. Page 1 - Col 2.
#Page 2
Page 2 - COl 1. Page 1 - Col 2.
考虑以下我的 pdf 文件中的页面数组images
。
{0: 'pdfpage_1.png', 1: '/pdfpage_2.png'}
在documentColumns
定义的列区域以下:
{'0': {'position': '30'}, '1': {'position': '60'}}
# Make table layout for each page (in images{})
for idx, (key, image) in enumerate(images.items()):
firstWidth = 0
#On each page, crop it according to my columns.
for i, col in enumerate(documentColumns):
columnPos = documentColumns.get(str(col))
pixelsrightcorner = round(width * (float(columnPos['position']) / 100))
area = (firstWidth, 0, pixelsrightcorner, float(height))
image_name = str(idx) + '_' + str(i + 1) + '.png'
output_image = img.crop(area)
output_image.save(image_name, image_type.upper())
cmd = [TESSERACT, image_name, '-', 'quiet']
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, bufsize=0, text=True, shell=False)
out, err = proc.communicate()
现在out
返回在图像上找到的文本。然后我说,在同一个循环中,对于返回文本中的每一行,将其添加到我的列表中:
for line in out.splitlines():
column.append({str(i): str(line)})
# Create JSON file.
f = open('myfile.json', "w+")
f.write(json.dumps(column))
f.close()
上面生成了这个:
[{
"0": "Page 1 - Col 1."
}, {
"0": ""
}, {
"1": "Page 1 - Col 2."
}, {
"1": ""
}, {
"0": "Page 2 - Col 1."
}, {
"0": ""
}, {
"1": "Page 2 - Col 2."
}, {
"1": ""
}]
预期产出
我正在尝试"从左到右"阅读每一页。这意味着最终输出应该是一个字典列表,其中每个字典代表一个新行,其中包含n
列数,如下所示:
[{
"0": "Page 1 - Col 1.",
"1": "Page 1 - Col 2."
},{
"0": "",
"1": ""
},{
"0": "Page 2 - Col 1.",
"1": "Page 2 - Col 2."
},{
"0": "",
"1": ""
}]
您可以声明一个数组而不是列表并转到添加字典
column = []
在循环中之后
node = {}
for line in out.splitlines():
node[str(i)] = str(line)
column.append(node)