映射两个不同的列表

2024-06-25 07:12:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我陷入困境。你知道吗

我正在搜索dd中的页眉和页脚

当我找到一个页眉时,我把它放在一个列表中——页脚也是如此。你知道吗

但是我注意到,有时页脚会出现在页眉之前,在这种情况下,我会检查headerlist是否为空,如果为空,则忽略页脚。 这个很好用。你知道吗

   if not header:
       footer.append(myfooter)

然而有时我会找到一个页眉,然后是两个页脚,然后又是一个页眉。然后这些被添加到一个列表-这不是我的目标。你知道吗

我的目标是映射页眉和页脚,只要它们紧跟在一个页眉和另一个页脚之后。因此,两个列表的数量应该总是相同的,或者headerlist应该大于footerlist。你知道吗

有没有什么办法来实现相应的算法?你知道吗


Tags: 目标列表数量ifnot情况ddheader
2条回答

这就是你想要的吗?我不知道“dd”是什么,我假装页眉和页脚是以特定方式开始的单行。您需要替换匹配页眉和页脚的逻辑,以适合您的用例。你知道吗

import re

VALID_DOCUMENT_A = \
"""
header: 1
Hi there.
This is the body of page 1.
footer: 1
header: 2
This is the second page.
footer: 2
"""

VALID_DOCUMENT_B = \
"""
header: 1
Hi there.
This is the body of page 1.
footer: 1
header: 2
This is the second page.
footer: 2
header: 3
This third page has a header but no footer.
"""

INVALID_DOCUMENT_A = \
"""
header: 1
Hi there.
This is the body of page 1.
footer: 1
This is the second page. Where's the header, though?
footer: 2
"""

INVALID_DOCUMENT_B = \
"""
header: 1
Hi there.
This is the body of page 1.
footer: 1a
footer: 1b
This is the second page. Oops - two footers above.
footer: 2
"""

INVALID_DOCUMENT_C = \
"""
header: 1
Hi there.
This is the body of page 1.
footer: 1
header: 2a
header: 2b
This is the second page. Oops - two headers above.
footer: 2
"""


def is_header(line):
    return re.match('^header:.*', line)


def is_footer(line):
    return re.match('^footer:.*', line)


def pair_headers_and_footers(text):
    lines = text.splitlines()

    stack = []
    for i, line in enumerate(lines, 1):
        if is_header(line):
            if stack:
                raise ValueError('Got unexpected header on line {}'.format(i))

            stack.append(line)

        elif is_footer(line):
            if not stack:
                raise ValueError('Got unexpected footer on line {}'.format(i))

            yield stack.pop(), line


if __name__ == '__main__':
    documents = [
        VALID_DOCUMENT_A,    # 2 headers, 2 footers
        VALID_DOCUMENT_B,    # 3 headers, 2 footers
        INVALID_DOCUMENT_A,  # missing header for page 1
        INVALID_DOCUMENT_B,  # multiple footers for page 1
        INVALID_DOCUMENT_C   # multiple headers for page 2
    ]

    for document in documents:
        try:
            print(list(pair_headers_and_footers(document)))
        except ValueError as e:
            print(e)

输出

[('header: 1', 'footer: 1'), ('header: 2', 'footer: 2')]
[('header: 1', 'footer: 1'), ('header: 2', 'footer: 2')]
Got unexpected footer on line 7
Got unexpected footer on line 6
Got unexpected header on line 7

附录

我应该在函数pair_headers_and_footers中添加以下内容:

lines = text.splitlines()

使用:

lines = (m.group(0).rstrip() for m in re.finditer('(.*\n|.+$)', text))

这可能有助于减少内存使用,特别是在处理大量文本时。通过这种修改,页眉和页脚配对的整个过程变得“懒惰”。你知道吗

仅当最后看到的项目是页眉时才向列表中添加页脚。这就是你想做的吗?你知道吗

相关问题 更多 >