列表元素的条件选择

2024-06-02 08:55:17 发布

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

我想从word文档中提取调查问题和调查项目(分别用标题2和标题3格式化)

在使用docx模块将word文档的所有段落导入python并读取之后,如果将所有段落都包含在一个总列表中,我会遇到以下问题:

当存在列表元素的子集(在本例中,所有列表元素的格式为“标题3”)时,我希望将所有这些元素以这种格式添加到一个独特的列表中,直到有一个段落未以“标题3”格式设置

如果另一个列表元素子集出现“header 3”,我想将它们添加到另一个列表中

我已经创建了一个字典,其中键是调查问题,值是一个空列表,需要用单个项目列表替换

import docx
import random
import string

doc = docx.Document('test2.docx')

all_paras = doc.paragraphs


questions = []
items = []
questions_and_items = {}
items_group = []

# questions#

for paragraph in all_paras:
    if paragraph.style.name.startswith('Heading 2'): 
        questions.append(paragraph.text)

# answer items#

for paragraph in all_paras:
    if paragraph.style.name.startswith('Heading 3'):
        items.append(paragraph.text)

# prepare keys of list

for question in questions:
    questions_and_items[question] = []

我现在的问题是:提取与特定问题相关的、合适的元素子列表并将它们添加到字典中合适的关键字的最佳方法是什么


Tags: inimport元素标题列表for格式items
1条回答
网友
1楼 · 发布于 2024-06-02 08:55:17

试着在段落中做一个循环,边走边添加q/a组合

import docx

def get_q_a(paragraphs, is_question, is_answer):
    question = None
    answers = []
    q_and_a = {}
    for paragraph in paragraphs:
        if is_question(paragraph):
            if question is not None:
                q_and_a[question] = answers
            question = paragraph
            answers = []
        elif is_answer(paragraph):
            answers.append(paragraph)
    if question is not None:
        q_and_a[question] = answers
    return q_and_a

if __name__ == '__main__':
   doc = docx.Document('test2.docx')
   print(get_q_a(doc.paragraphs,
                 lambda p: p.style.name.startswith('Heading 2'),
                 lambda p: p.style.name.startswith('Heading 3')))

相关问题 更多 >