python - How to replace multiple words in .docx file and save the docx file using python-docx
问题描述
I'm trying to change the content of the docx using python-docx library. My changes are about replacing the words. So, I have list of words Original word list: ['ABC','XYZ']
which I need to replace with revised word list: ['PQR', 'DEF']
. I also need to preserve the format of these words. Right now, I can save only one change. Here is my code for the reference.
def replace_string(filename='test.docx'):
doc = Document(filename)
list= ['ABC','XYZ']
list2 = ['PQR','DEF']
for p in doc.paragraphs:
print(p.text)
for i in range(0, len(list)):
if list[i] in p.text:
print('----!!SEARCH FOUND!!------')
print(list[i])
print(list2[i])
print('\n')
inline = p.runs
# Loop added to work with runs (strings with same style)
for i in range(len(inline)):
#print(inline[i].text)
if list[i] in inline[i].text:
print('----SEARCH FOUND!!------')
text = inline[i].text.replace(list[i], list2[i])
inline[i].text = text
print(inline[i].text)
doc.save('dest1.docx')
return 1
replace_string()
Original content of test.docx file:
ABC
XYZ
Revised content or saved content of dest1.docx file:
PQR
XYZ
How can I save all the replacements? The list of word may increase and its size is not fix.
解决方案
以下代码对我有用。这也保留了格式。希望这对其他人有帮助。
def replace_string1(filename='test.docx'):
doc = Document(filename)
list= ['ABC','XYZ']
list2 = ['PQR','DEF']
for p in doc.paragraphs:
inline = p.runs
for j in range(0,len(inline)):
for i in range(0, len(list)):
inline[j].text = inline[j].text.replace(list[i], list2[i])
print(p.text)
print(inline[j].text)
doc.save('dest1.docx')
return 1
推荐阅读
- python - Python:在循环/暂停执行线程后杀死线程
- owl - Jena Reasoner 和属性推理
- angular - 如何在 Paytm 迷你应用中实现登录
- mongodb - $in 运算符在 MongoDB 聚合中不起作用
- c# - 使用 TLS 1.2 和使用 MVC 5 应用程序的特定密码套件连接到网站
- java - 我们有 Java 的 MIDL RPC 代码生成器吗?
- php - 如何确定ajax响应是键值对数组还是简单字符串响应
- sql - AWS Redshift - 相关查询
- android - Android模拟器屏幕在旋转时崩溃
- python - 从 OpenCV 描述符中提取信息