python实现word文档多内容替换

直接上代码:

利用docx读取.docx格式

利用win32com模块对.doc文档转为docx

 

脚本调用: python your.py your.doc/your.docx 被替换字符A/被替换字符B/被替换字符C 替换字符a/替换字符b/替换字符c

from win32com import client as wc
import os
import docx
import sys

def help():
    print("Format: python py_file path+filename.doc/.docx A/B/C a/b/c\n"
          "eg: python preplace_string.py E:/....../a.docx 你好/好的/谢谢 你好啊/嗯嗯/不客气\n"
          "eg: python preplace_string.py E:/....../a.doc 你好/好的/谢谢 你好啊/嗯嗯/不客气\n"
		  "EXE:\n"
		  "eg: preplace_string.exe E:/....../a.doc 你好/好的/谢谢 你好啊/嗯嗯/不客气\n"
		  "eg: preplace_string.exe E:/....../a.docx 你好/好的/谢谢 你好啊/嗯嗯/不客气\n"
          "替换字符串与被替换字符串一一对应,不同字符串用/分割\n")
if __name__=='__main__':
    #print(sys.argv)
    num=len(sys.argv)

    if(num!=4):
        help()
        sys.exit(1)

    path=sys.argv[1]#file
    if not os.path.exists(path):
        print(path,'does not exist!!!!!\n')
    path=os.path.abspath(path)
    basename,ext=os.path.splitext(path)
    if ext=='.doc':
        try:
            #webbrowser.open(path)
            word = wc.Dispatch("Word.Application")
            doc = word.Documents.Open(path)
            doc.SaveAs(basename+'.docx', 12)# 12为docx
            doc.Close()
            word.Quit()
        except:
            print("can not read "+path+"!\nPlease check out that whether the format of the file is doc/docx Or Does this file exist!!!")
            sys.exit(1)
    elif ext!='.docx':
        print("can not read" + path + "!\nPlease check out that whether the format of the file is doc/docx!!!")
        sys.exit(1)
    old_string=sys.argv[2]#old_string="你好|好的|谢谢"
    new_string=sys.argv[3]#new_string="你好啊|嗯嗯|不客气"
    olds=old_string.split('/')
    news=new_string.split('/')
    if(len(olds)!=len(news)):
        print('The number of replacement strings does not match the number of replaced strings,Please Check!')
        print('Old string:',olds)
        print('New string:',news)
        sys.exit(1)

 
    path=basename + '.docx'
    file =docx.Document(path)

    for i in range(len(olds)):
        for paragraph in file.paragraphs:
            paragraph.text = paragraph.text.replace(olds[i],news[i])
    #file.save('test'+'_temp.docx')
    file.save(basename + '_temp.docx')
    print('succes!\n'
          'new file is shown in ' + basename+'_temp.docx')

 

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值