用嵌套循环创建一个键值列表



所以我有一个脚本,可以检查PDF文件中的每个页面,然后在每个页面上,将PDF文件的文本分为列。

考虑以下列:

{"1":{"position":"15"}, "2":{"position": "50"}}'
pages = {}
npages = 2 #Number of pages in the PDF.
for n in range(npages):
    pages[n + 1] = []
    for i, col in enumerate(COLUMNS):
        out = "Page n Column 1 Text Column 2 Text" #Simplified string.
        pages[n + 1].append({int(i + 1): str(out)})

我的假设是,这将创建一个钥匙值对,例如:

page n: text inside the column

由于某种原因,上面的脚本会创建这样的对:

{1: 'Page 1 Column 1 Text'} - {2: 'Page 1 Column 2 Text'}
{1: 'Page 2 Column 1 Text'} - {2: 'Page 2 Column 2 Text'}

如您所见,它创建了键,例如:

{1: 'Page 1 Column 1 Text'}

假设我想这样做:(输出值是第一次迭代(

for page, column in pages.values():
    print("Page: {}".format(page)) #Should output: Page: 1
    print("Column Text: {}".format(column)) #Should output: Column Text: Column 1 Text

总结一下,我所需的输出是(页码是密钥,列文本为值(:

{1: 'Page 1 Column 1 Text'}
{1: 'Column 2 Text'}
{2: 'Page 2 Column 1 Text'}
{2: 'Column 2 Text'}

我想念什么?如果这是基本的,我很抱歉,我是Python的新手。

似乎您只需要一个页面列表:

pages = []
npages = 2  # Number of pages in the PDF.
COLUMNS = ["example1", "example2", "example3"]
for n in range(npages):
    for i, col in enumerate(COLUMNS):
        if i == 0:
            pages.append({n + 1: "Page {} Column {} {}".format(n + 1, i + 1, col)})
        else:
            pages.append({n + 1: "Column {} {}".format(i + 1, col)})
然后,页面将定义为:
[{1: 'Page 1 Column 1 example1'},
 {1: 'Column 2 example2'},
 {1: 'Column 3 example3'},
 {2: 'Page 2 Column 1 example1'},
 {2: 'Column 2 example2'},
 {2: 'Column 3 example3'}]

更新每个注释:列表不是以这种方式解析内容的理想方式 - 如果您试图访问每个页面的列内容,那么dicts的dict会更有意义。例如:

pages = {}
npages = 2  # Number of pages in the PDF.
COLUMNS = ["example1", "example2", "example3"]
for n in range(npages):
    page_name = "Page {}".format(n + 1)
    pages[page_name] = {}
    for i, col in enumerate(COLUMNS):
        column_name = "Column {}".format(i + 1)
        pages[page_name][column_name] = col

导致页面定义为:

{
    'Page 1': {
        'Column 1': 'example1',
        'Column 2': 'example2',
        'Column 3': 'example3'
    },
    'Page 2': {
        'Column 1': 'example1',
        'Column 2': 'example2',
        'Column 3': 'example3'
    }
}

最新更新