将字典追加到列表

时间:2019-07-11 11:54:22

标签: python json python-3.7

请考虑以下列表:

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": ""
}]

1 个答案:

答案 0 :(得分:0)

您可以声明一个数组,而不是列表,然后添加字典

column = []

循环后

node = {}

for line in out.splitlines():
    node[str(i)] = str(line)

column.append(node)
相关问题