python-docx 带base64图片写入
富文本数据见data.txt
我自己的思路是
1、将原始记录中base64图片信息记录提取到变量中存储。
2、将富文本数据去除格式,并将图片内容替换成文本(待替换的图片)。
3、使用python-docx库进行相关数据写入。
问题:
目前没有较好的方法将对应位置的图片替换插入。
当前效果:
预期效果:
with open("data.txt",encoding='utf-8',mode='r') as f:
res = eval(f.read());
question_images = re.findall(pattern_pic, res[0][6]) # 将问题描述的图片存放起来
solder_images = re.findall(pattern_pic, res[0][7]) # 将解决方案的图片存放起来
doc = Document() # 定义doc文档
def html_display(new_recods):
new_recods = re.sub(pattern_pic, "待替换图片", new_recods)
new_recods = BeautifulSoup(new_recods, 'html.parser').get_text() # 去除html 语言
new_recods = re.sub('\s*\r', '', new_recods) # 将里面多余的换行去掉。
print(new_recods)
return new_recods
def write_querydate():
question_desc = html_display(res[0][6]) # 将base64替换为待替换图片字眼
question_solder = html_display(res[0][7])
"""设置正文字体格式"""
doc.styles['Normal'].font.name = u'宋体'
doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
# 写入问题编号
doc.add_heading("问题编号:", level=0).add_run(res[0][0])
doc.add_heading("问题主题:", level=2).add_run(res[0][2])
doc.add_heading("问题描述:", level=3) # 写入问题描述章节
p1 = doc.add_paragraph(question_desc)
doc.add_heading("解决方案:", level=3) # 写入问题描述章节
p2 = doc.add_paragraph(question_solder)
doc.save("test.docx")
这种文档手动最方便[手动狗头]