怎么找到目标内容 插入一句话 在目标内容的上一个段落

下面的这个不对

def insert_template(file_id, target_title):
    doc = aw.Document(file_id)
    # 创建一个DocumentBuilder对象
    builder = aw.DocumentBuilder(doc)
    # 遍历文档节点找target_title
    paragraphs = doc.get_child_nodes(aw.NodeType.PARAGRAPH, True)
    for i, paragraph in enumerate(paragraphs):
        if target_title in paragraph.to_string(aw.SaveFormat.TEXT).strip() and "start" not in paragraph.to_string(
                aw.SaveFormat.TEXT).strip():
            # 找到目标标题,将光标移到其前
            if i > 0:
                prev_paragraph = paragraphs[i+1]
                builder.move_to(prev_paragraph)
                builder.insert_paragraph()
                builder.writeln("start")
            # 接下来不需要继续查找,跳出循环
            break
    task_id = str(uuid.uuid4())
    file_path = os.path.join(settings.DOWNLOAD_PATH, f"hhhhfdf.docx")
    doc.save(file_path)
    return file_path

@hhh1111 您可以使用下面的代码获取前一个段落:

paragraphs = doc.get_child_nodes(aw.NodeType.PARAGRAPH, True)
for paragraph in paragraphs:
    if target_title in paragraph.to_string(aw.SaveFormat.TEXT).strip() and "start" not in paragraph.to_string(
            aw.SaveFormat.TEXT).strip():
        # 找到目标标题,将光标移到其前
        paragraph = paragraph.as_paragraph()
        prev_para = paragraph.previous_sibling
        if prev_para is None:
            builder.move_to_document_start()
        else:
            builder.move_to(prev_para)

        builder.insert_paragraph()
        builder.write("start")
        # 接下来不需要继续查找,跳出循环
        break

有用的链接