【问题标题】:Appending dicts to a list将字典附加到列表
【发布时间】:2019-07-11 11:54:22
【问题描述】:

考虑以下列表:

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.

考虑下面的数组 images 我的 pdf 文件中的页面。

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

【问题讨论】:

    标签: python json python-3.7


    【解决方案1】:

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

    column = []
    

    在循环之后

    node = {}
    
    for line in out.splitlines():
        node[str(i)] = str(line)
    
    column.append(node)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-15
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多