import os
from docx import Document
# 放了一些docx 文件
old_file_path = "D:/test"
# 生成新文件后的存放地址
new_file_path = "D:/test/a"
replace_dict = {
"TS-PM-434诃子肉饮片工艺规程(A00版)": "TS-PM-K434诃子肉饮片工艺规程(A00版)",
}
def check_and_change(document, replace_dict):
"""
遍历word中的所有 paragraphs,在每一段中发现含有key 的内容,就替换为 value 。
(key 和 value 都是replace_dict中的键值对。)
"""
for para in document.name:
for i in range(len(para.runs)):
for key, value in replace_dict.items():
if key in para.runs[i].text:
print(key+"-->"+value)
para.runs[i].text = para.runs[i].text.replace(key, value)
return document
def main():
for name in os.listdir(old_file_path):
print(name)
old_file = old_file_path + name
new_file = new_file_path + name
if old_file.split(".")[1] == 'docx':
document = Document(old_file)
document = check_and_change(document, replace_dict)
document.save(new_file)
print("^"*30)
if __name__ == '__main__':
main()
202104修改文件名
最新推荐文章于 2026-06-28 17:29:25 发布
本文介绍了一个Python脚本,通过导入docx库,实现对指定目录下docx文件中特定内容的查找并替换,使用了check_and_change函数进行逐段查找和替换操作。主要关注文档处理和字符串替换技术在实际工作中的应用。
3402

被折叠的 条评论
为什么被折叠?



