• Python小程序之sed命令替换


    需求:

      编写sed命令脚本

    代码如下

     1 # Author:Lee Sir
     2 
     3 import sys,os
     4 
     5 des_file = r'E:StartPythonday3	est.txt'
     6 des_file1 = r'E:StartPythonday3	est1.txt'
     7 
     8 parameter = ['0','Somehow','123',des_file]
     9 
    10 def usage(parameter):
    11     if len(parameter) == 4:
    12         if isinstance(parameter[1],str) and isinstance(parameter[2],str):
    13             old_str = parameter[1]
    14             new_str = parameter[2]
    15             if os.path.exists(parameter[3]):
    16                 des_file = parameter[3]
    17                 return True, old_str, new_str, des_file
    18     return False
    19 
    20 def check_string_exist(old,file):
    21     with open(file,encoding='utf-8') as fd:
    22         for line in fd:
    23             if old not in line:
    24                 return False
    25             else:
    26                 return True
    27 
    28 def replace(old,new,file):
    29     with open(file,'r+',encoding='utf-8') as fd,open(des_file1,'w+',encoding='utf-8') as fd1:
    30         for line in fd:
    31             if old in line:
    32                 new_line = line.replace(old,new)
    33             else:
    34                 new_line = line
    35             print(new_line)
    36             fd1.write(new_line)
    37 
    38 def main():
    39     result = usage(parameter)
    40     if result:
    41         if check_string_exist(result[1],result[3]):
    42             replace(result[1],result[2],result[3])
    43         else:
    44             print('the %s is not found in %s ' % (result[1],result[3]))
    45     else:
    46         exit('USAGE: %s  old_str  new_str  des_file' % sys.argv[0])
    47 
    48 if __name__ == '__main__':
    49     main()
  • 相关阅读:
    [HNOI2015]实验比较 树形dp+组合数学
    【bzoj1090】 [SCOI2003]字符串折叠
    hdu4514(非连通图的环判断与图中最长链)(树的直径)
    数据类型进阶 续1
    数据类型进阶
    二进制补码
    基本数据类型的包装类
    变量的作用域
    用变量保存多种类型的数据
    用变量简化计算
  • 原文地址:https://www.cnblogs.com/dachenzi/p/6595910.html
Copyright © 2020-2023  润新知