背景需求
学期总结开始写各种总结

同事请我代写

我手里写5个老师要写。就想试试能不能用"星火讯飞写稿子"+Python(excle \word)批量生成)
一、AI生成读后感
星火讯飞写出来的读后感内容相同,所以要用不同的关键词
1、不同岗位:假如您是一位班主任、假如您是一位幼儿园管理者、假如您是一位保育工作者)
2、同样都是幼儿老师,就在"于漪老师事迹"后面写,围绕"幼儿发展优先分析""谈谈师幼互动""结合理解发现支持幼儿"等不同的元素写
3、字数是1000字。但总体感觉很少,下次用2000字,但可能也就1000字
篇幅有限这里不介绍如何获取读后感文字,只是把文字都贴入EXCLE的content内


从AI复制的读后感,要选中单元格,点击顶部的输入框,把文字全部贴入,这样文字都在一个单元格里,才能一次性写入(重要)

此外每个单元格第一行要空(手动换行符)


二、删除单元格里的手动换行符
测试后发现还是需要再EXCEL里删除手动换行符(空行),而不是在Python里修改
EXCEL用VBA宏进行换行符的替换

第1步:在EXCEL界面上ALT+F11

第2步:VBA窗体 插入-模块

第3步:黏贴代码

VBA代码
Sub 删除单元格内空行()
Dim cell As Range
For Each cell In Selection
If InStr(cell.Value, Chr(10)) > 0 Then
cell.Value = Replace(cell.Value, Chr(10), "123")
End If
Next cell
End Sub
第4步:两次关闭

第5步:选中读后感(有换行符空行)

第6步:开发工具-宏-选中刚才代码-运行
第7步:所有换行符空行都被改成123(如果有两个123,说明这里面有两个连续的换行符也就是一个是空行)

保存EXCEL关闭


三、制作WORD模版
本次需要制作两个内容相同,标题不同的读后感

(一)工会学后感
原始样式

修改后样式

(二)校本研修小结
原始样式

修改后样式

特别说明:
读后感content部分的字体是宋体小四,但是我每次导入后,会变成宋体小五

原来是模版里预设的正文样式字体就是宋体小五。所以我把正文样式字体改成小四,就解决了问题。

四、EXCEL制作


五、代码展示
python
from docxtpl import DocxTemplate
import pandas as pd
import os,time
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt
import win32com.client as win32
from docxtpl import DocxTemplate
import pandas as pd
import os
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt
import win32com.client as win32
zpath = r'C:\Users\jg2yXRZ\OneDrive\桌面\校本研修'
print('-------------1、生成WORD-------------')
n=['工会学后感','校本研修小结']
for x in n:
template_path = os.path.join(zpath, f'{x}.docx')
output_path = os.path.join(zpath, '整理')
os.makedirs(output_path, exist_ok=True)
tpl = DocxTemplate(template_path)
autho = pd.read_excel(os.path.join(zpath, 'autho.xlsx'))
num = autho["num"].astype(str).str.rstrip() #
name = autho['name'].str.rstrip() #
title = autho['title'].str.rstrip()
content = autho['content'].str.rstrip()
# print
num1 = autho.shape[0]
for i in range(num1):
context = {
"num": num[i],
"name": name[i],
"title": title[i],
"content": content[i],
}
tpl = DocxTemplate(template_path)
tpl.render(context)
output_filename = f"{int(num[i]):02} {name[i]} {x}.docx"
output_file_path = os.path.join(output_path, output_filename)
# try:
tpl.save(output_file_path)
print('-------------2、123替换硬回车和缩进四字符-------------')
def replace_text_in_docx(docx_path, old_text, new_text):
doc = Document(docx_path)
for para in doc.paragraphs:
if old_text in para.text:
para.text = para.text.replace(old_text, new_text)
doc.save(docx_path)
for root, dirs, files in os.walk(output_path):
for file in files:
if file.endswith(".docx"):
file_path = os.path.join(root, file)
replace_text_in_docx(file_path, "123123", "\n ")
replace_text_in_docx(file_path, "123", "\n ")
print('-------------3、删除第一个软回车-------------')

(一)获取有123的文档


(二)123变成软回车(替换原来位置)
(三)删除第一个软回车
本文样式是前面5行要的,第6行就是第一段内容,因此这里多的一个软回车需要删除
