[英]Python chunk list from one element to another
我有以下代码:
for paragraph in document.paragraphs:
while paragraph.style.name == 'Heading 2':
print(paragraph.style.name)
print(paragraph.text)
这基本上行不通,因为我不知道如何适应正确的逻辑。 我正在使用 python docx 库https://python-docx.readthedocs.io/en/latest/user/styles-using.html遍历文档的段落。
现在,我想从每个Heading 2
开始将段落列表拆分为子列表,然后添加具有不同paragraph.style.name
的所有下一段直到下一个Heading 2
元素,这样每个块将包含一个Heading 2
段落及其相应的文字。
换句话说,我正在寻找一种方法将列表分成从一个元素到另一个元素的块。 请帮忙:)
您可以使用itertools.groupby
来完成此操作:
from itertools import groupby
groups, next_group = [], []
for k, group in groupby(document.paragraphs, lambda x: x.style.name == 'Heading 2'):
# If the predicate is True and next_group is populated,
# we create a new chunk
if k and next_group:
groups.append(next_group)
next_group = []
# Fill up the current chunk
for paragraph in group:
# feel free to swap this out with a print statement
# or whatever data structure suits you
next_group.append({'style_name': paragraph.style.name, 'text': paragraph.text})
为了清楚起见,我在这里使用字典列表,但您可以替换任何数据结构
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.