考虑以下列表:
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": ""
}]
我试着“从左到右”阅读每一页。这意味着最终输出应该是一个dict列表,其中每个dict代表一个新行,包含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": ""
}]
您可以声明一个数组而不是列表,然后转到添加dict
在循环中之后
相关问题 更多 >
编程相关推荐