在python-docx中,paragraph
对象有一个insert_paragraph_before方法,允许在其自身之前插入文本:
p.insert_paragraph_before("This is a text")
虽然没有insert_paragraph_after
方法,但我认为段落对象对自身有足够的了解,可以确定列表中的下一个段落。不幸的是,python-docx AST的内部工作原理有点复杂(并且没有真正的文档)。
我想知道如何使用以下规范编写函数?
def insert_paragraph_after(para, text):
发布于 2018-02-07 23:04:17
试图理解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()
发布于 2018-02-07 23:41:48
与此同时,我发现了另一种方法,更高层次的(尽管可能不是那么优雅)。它本质上是找到父级,列出子级,计算出自己在队列中的位置,然后获得下一个位置。
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
一个优点是,它最大限度地避免了进入内部工作。
发布于 2018-12-13 21:04:52
请参阅以下详细信息:
para1 = document.add_paragraph("Hello World")
para2 = document.add_paragraph("Testing!!")
p1 = para1._p
p1.addnext(para2._p)
https://stackoverflow.com/questions/48663788
复制相似问题