python-docx:之后插入一个段落

时间:2018-02-07 12:26:25

标签: python python-docx

在python-docx中,p.insert_paragraph_before("This is a text") 对象有一个允许在自身之前插入文本的方法insert_paragraph_before

insert_paragraph_after

没有def insert_paragraph_after(para, text): 方法,但我认为段落对象足够了解自己,以确定列表中的下一个段落。不幸的是,python-docx AST的内部工作原理有点复杂(并没有真正记录)。

我想知道如何使用以下规范编写函数?

mysqldump

3 个答案:

答案 0 :(得分:2)

试图理解docx的内部工作方式让我头晕目眩,但幸运的是,它很容易实现你想要的东西,因为内部对象已经有了必要的方法addnext,这是我们所需要的一切:

from docx import Document

from docx.text.paragraph import Paragraph
from docx.oxml.xmlchemy import OxmlElement

def insert_paragraph_after(paragraph, text=None, style=None):
    """Insert a new paragraph after the given paragraph."""
    new_p = OxmlElement("w:p")
    paragraph._p.addnext(new_p)
    new_para = Paragraph(new_p, paragraph._parent)
    if text:
        new_para.add_run(text)
    if style is not None:
        new_para.style = style
    return new_para

def main():
    # Create a minimal document
    document = Document()
    p1 = document.add_paragraph("First Paragraph.")
    p2 = document.add_paragraph("Second Paragraph.")

    # Insert a paragraph wedged between p1 and p2
    insert_paragraph_after(p1, "Paragraph One And A Half.")

    # Test if the function succeeded
    document.save(r"D:\somepath\docx_para_after.docx")

if __name__ == "__main__":
    main()

答案 1 :(得分:1)

与此同时,我发现了另一种方法,更高级别(虽然可能不那么优雅)。它基本上找到父母,列出孩子,排成一行,然后得到下一个。

def par_index(paragraph):
    "Get the index of the paragraph in the document"
    doc = paragraph._parent
    # the paragraphs elements are being generated on the fly,
    # they change all the time
    # so in order to index, we must use the elements
    l_elements = [p._element for p in doc.paragraphs]
    return l_elements.index(paragraph._element)


def insert_paragraph_after(paragraph, text, style=None):
    """
    Add a paragraph to a docx document, after this one.
    """
    doc = paragraph._parent
    i = par_index(paragraph) + 1 # next
    if i <= len(doc.paragraphs):
        # we find the next paragraph and we insert before:
        next_par = doc.paragraphs[i]
        new_par = next_par.insert_paragraph_before(text, style)
    else:
        # we reached the end, so we need to create a new one:
        new_par = parent.add_paragraph(text, style)
    return new_par

一个优点是它主要避免进入内部工作。

答案 2 :(得分:0)

请参考以下详细信息:
para1 = document.add_paragraph(“ Hello World”
para2 = document.add_paragraph(“ Testing !!”)

p1 = para1._p
p1.addnext(para2._p)

Reference