繁体   English   中英

列表元素的条件选择

[英]Conditional selecting of list elements

我想从 word 文档中提取调查问题和调查项目(格式分别为 header 2 和 header 3 。

在将带有 docx 模块的 word 文档的所有段落导入并读取到 python 后,在总列表中包含所有段落时遇到以下问题:

当存在列表元素的子集时(在这种情况下,所有列表元素都被格式化为“header 3”)我想将所有这些具有这种格式的元素添加到一个独特的列表中,直到有一个段落没有被格式化为“header” 3"。

如果再次出现带有“标题 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] = []

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

尝试通过段落进行单循环,在 go 中添加 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')))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM