代码艺术家
Code artist

很喜欢释迦牟尼佛的一句话:“无论你遇见谁,他都是你生命该出现的人,绝非偶然,他一定教会你一些什么”。

有问题 问我 问Google

使用python做一个批量替换文档内容的脚本

最近做postgresql文档的时候,发现文档里有一些是pg文档特有的东西,我们需要对他进行去pg化,

相信国内很多公司也这样做吧,为了不泄露公司相关信息,字典部分没写全或者用特殊符号代替了。

     由于我是个初入门的pythoner所以发的代码不是很高级,如果有高见请多多交流,不胜感激!

以下是脚本代码:

 1 #!/usr/bin/env python
 2 #coding=utf-8
 3 import sys
 4 import re
 5 import glob
 6 import os.path
 7 import argparse
 8 import subprocess
 9 
10 source_root= '.'
11 
12 def sys_replace():
13     dic_sys = {
14                 'pgpass': 'xxx'  ,
15                 'PostgreSQL': '---'    
16 
17           }
18     all_files2replace(dic_sys)
19 def mis_replace():
20     dic_sys = {
21                 'pgpass': 'xxx'  ,
22                 'PostgreSQL': '---'  ,
23     all_files2replace(dic_sys)        
24 def other_replace():
25     dic_sys = {
26                 'pgAdmin':'xxx',
27              'psql': '---'  ,
28                'PSQL':'***'
29           }
30     all_files2replace(dic_sys)        
31 
32 def all_files2replace(dic):
33     files = os.listdir(source_root)
34     for file_name in files:
35         file_path =os.path.join(source_root,file_name)
36         fn=open(file_path,'r')
37         f=fn.read()
38         fn.close()
39         for i in dic.keys():
40             f=re.sub(i, dic[i],f)
41         fn=open(file_path,'w')
42         fn.write(f)
43         fn.close()
44 
45 def main():
46     sys_replace()
47     mis_replace()
48     other_replace()
49 if __name__ == "__main__":
50     if len(sys.argv)<2:
51         print '''缺少sgml文件所在文件的路径参数!
52 
53         --version :显示本工具信息。 
54         --help    :显示帮组信息。     
55         '''
56         sys.exit()
57     if sys.argv[1].startswith('--'):
58         option=sys.argv[1][2:]
59         if option == 'version':
60             print '''
61             版本v1.0。
62                         bug提交地址:278478993@qq.com
63                '''
64     elif option == 'help':
65             print '''
66                     书写格式:python <"脚本名"> <"sgml文件路径">  
67                   '''
68     else:
69             print '未知参数!'
70         sys.exit()
71     source_root=''.join(sys.argv[1:])
72     print ""
73     main()
74     print 'Converted to kingbase sucessfully!'
75     print ""

 

posted @ 2015-12-31 15:01  Jason‘  阅读(1053)  评论(0)    收藏  举报