python文本内容替换?

Python017

python文本内容替换?,第1张

这样编写:

fa=open("A.txt","r")

ta=fa.readlines()

fb=open("B.txt","r")

tb=fb.readlines()

tb[2:-9]=ta

fa.close()

fb.close()

fb=open("B.txt","w")

fb.writelines(tb)

fb.close()

编者的话(可以跳过):

    在政府单位实习了一段时间,发现有很多资料需要制作,而且繁琐重复,第一时间就想到了python,因为在办公自动化这方面我只知道python,本着能偷懒就偷懒的原则,通过查阅资料整出一个小脚本然后用tkinter的ui组件写了一个界面方便除我之外的人使用,此软件涉及内部文件就不发布了。截图如下:

需求如下:

    当你有一大堆的word文档,然后这些word文档都有其固定格式,也许是一个表格,也许就是只有文字的普通文档,这些固定模式的文档我称之为模板。如果有10份模板,这些模板的填写内容大致相同,比如说文件的编号,年份,一些公司名称等。然后基本上就是机械的找位子复制改改格式循环往复然后时间就过去了,做了一堆无意义的事情。

    所以核心功能:需要把自己想要填写的内容填写到模板的指定位置。

2、实现方式

2.1使用python-docx

    有兴趣的可以深入学习一下python-docx,这里仅仅是实现需求。python-docx只能处理docx所以doc需要转为docx具体方法可以自行百度。

    这个替换程序是可以替换word文档内表格和非表格的内容且不会修改原模板的任何格式,填写好上面所给函数的参数然后在ide里运行一下,前提是事先在文档中要填写的位置写好要替换的内容,也就是old_text,如下所示:

 媳妇有无数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()