问题;
,无法保留原文件内的图片
下面是问题的图片,左边为原word,右边是替换文字后保存的新word
以下是我的代码
部分代码借鉴与下面文章[]https://blog.csdn.net/weixin_39988197/article/details/109858965)
修改处理后的代码如下
# coding=utf-8
import os
from docx import Document
old_file_path = r"C:\Users\Administrator\Desktop\新建文件夹 (5)\需要替换的word\\" # 已有word的原始地址
new_file_path = r"C:\Users\Administrator\Desktop\新建文件夹 (5)\新替换的word\\" # 生成新文件后的存放地址
op = open(r'C:\Users\Administrator\Desktop\新建文本文档.txt', "r") # 打开并读取txt内容,将txt内容写入空字典
replace_dict = {} #新建空字典
while True:
line = op.readline()
index = line.find(' ') # 以空格为分割
key = line[:index]
value = line[index:]
replace_dict[key] = value
if line == '':
break
op.close() # 关闭打开的txt
print(replace_dict)
def check_and_change(document, replace):
"""
遍历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.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()
运行后的效果
运行后看pycharm中显示的效果,我本以为很成功,打开保存后的word,发现之前word内的照片全没了,这下让我陷入了沉思
我学习python半个多月,研究了好久也没能解决这个问题,在这里咨询一下大家,
如何能让程序运行替换word内文字后,保存原来图片不变只替换文字呢