标签:批量替换 https tables 编号 docx network ocx 需求 work
有一个需求需要把word中的一段文档的编号批量替换
如,把133-183批量的替换成31-81,需要批量的替换word,脚本如下
from docx import Document
import os
oldFile = "C:\\Users\\wuzs\\Desktop\\test.docx"
newFile = "C:\\Users\\wuzs\\Desktop\\test2.docx"
DICT = {
"SP_OS_NETWORK_133":"SP_OS_NETWORK_031",
"SP_OS_NETWORK_134":"SP_OS_NETWORK_032",
"SP_OS_NETWORK_135":"SP_OS_NETWORK_033",
"SP_OS_NETWORK_136":"SP_OS_NETWORK_034",
*****************
*****************
"SP_OS_NETWORK_182":"SP_OS_NETWORK_080",
"SP_OS_NETWORK_183":"SP_OS_NETWORK_081",
}
def main():
document = Document(oldFile)
document = check(document)
document.save(newFile)
def check(document):
# tables
for table in document.tables:
for row in range(len(table.rows)):
for col in range(len(table.columns)):
for key, value in DICT.items():
if key in table.cell(row, col).text:
print(key + "->" + value)
table.cell(row, col).text = table.cell(row, col).text.replace(key, value)
# paragraphs
for para in document.paragraphs:
for i in range(len(para.runs)):
for key, value in 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
if __name__ == '__main__':
main()
标签:批量替换 https tables 编号 docx network ocx 需求 work
原文地址:https://www.cnblogs.com/mrwuzs/p/11444594.html