第1个回答 2022-06-16
媳妇有无数word文档要替换,百度后发现没有现成的方法。
google后没有太合适的。抄抄写写弄个python脚本换目录下所有word内容,共勉之。
import os
from docx import Document
# 放了一些docx 文件
files_dict ={
"/home/test/a/医疗器械临床试验第一版-设计/": "/home/test/a/医疗器械临床试验第一版-设计/",
"/home/test/a/医疗器械临床试验第一版-管理制度/": "/home/test/a/医疗器械临床试验第一版-管理制度/",
"/home/test/a/医疗器械临床试验第一版-SOP/": "/home/test/a/医疗器械临床试验第一版-SOP/",
"/home/test/a/目录/": "/home/test/a/目录/"
}
replace_dict = {
"XXGNK":"XZDXGWK",
"心血管专业": "心脏大血管外科",
"心血管":"心脏大血管外科",
}
def check_and_change(document, replace_dict):
"""
遍历word中的所有 paragraphs,在每一段中发现含有key 的内容,就替换为 value 。
(key 和 value 都是replace_dict中的键值对。)
"""
for para in document.paragraphs:
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)
for table in document.tables:
for row in table.rows:
for cell in row.cells:
for para in cell.paragraphs:
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 old_file_path, new_file_path in files_dict.items():
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()