Python 文档:insert_after()?
Python docx: insert_after()?
现在,我有一个 "template file",其中有几个段落(如教育、职业、目标等),每个段落的组成方式如下
1. Education
2. Career
3. Aims
现在,我想用数据库中的文本填充这些段落,使其看起来像
1. Education
some education text from the database
2. Career
some nasty career stuff from the database
3. Aims
some aims defined here from the database
我搜索了 API 文档,但只找到一个名为 insert_paragraph_before(text)
的关闭函数 - 是否存在对应的函数?
所需的输出应为:
from docx import Document
document = Document('template.docx')
for p in document.paragraphs:
if p.text == 'some keyword here':
p.insert_paragraph_after('some text to insert here')
^
|
function does not (yet?) exist
document.save('result.docx')
简短的回答是 "not yet"。
虽然你可以做的是这样的事情:
def insert_paragraph_after(paragraphs, idx, text=None):
next_paragraph_idx = idx + 1
if idx == len(paragraphs):
return document.add_paragraph(text)
next_paragraph = paragraphs[next_paragraph_idx]
return next_paragraph.insert_paragraph_before(text)
paragraphs = list(document.paragraphs)
for idx, paragraph in enumerate(paragraphs):
if paragraph.text == 'some keyword':
insert_paragraph_after(paragraphs, idx, "Some lorem ipsum here")
现在,我有一个 "template file",其中有几个段落(如教育、职业、目标等),每个段落的组成方式如下
1. Education
2. Career
3. Aims
现在,我想用数据库中的文本填充这些段落,使其看起来像
1. Education
some education text from the database
2. Career
some nasty career stuff from the database
3. Aims
some aims defined here from the database
我搜索了 API 文档,但只找到一个名为
insert_paragraph_before(text)
的关闭函数 - 是否存在对应的函数?
所需的输出应为:
from docx import Document
document = Document('template.docx')
for p in document.paragraphs:
if p.text == 'some keyword here':
p.insert_paragraph_after('some text to insert here')
^
|
function does not (yet?) exist
document.save('result.docx')
简短的回答是 "not yet"。
虽然你可以做的是这样的事情:
def insert_paragraph_after(paragraphs, idx, text=None):
next_paragraph_idx = idx + 1
if idx == len(paragraphs):
return document.add_paragraph(text)
next_paragraph = paragraphs[next_paragraph_idx]
return next_paragraph.insert_paragraph_before(text)
paragraphs = list(document.paragraphs)
for idx, paragraph in enumerate(paragraphs):
if paragraph.text == 'some keyword':
insert_paragraph_after(paragraphs, idx, "Some lorem ipsum here")