zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    【NOI D2T1】量子通信(容斥原理+卡常)
    CF1555D Say No to Palindromes(线段树)
    CF1554B Cobb
    CF1554A Cherry
    【做题笔记】UVA10162 Last Digit
    【做题记录】CF1223D Sequence Sorting
    CF39H
    UVA10763
    题解 AT2361 [AGC012A] AtCoder Group Contest
    このブログについて | About this blog
  • 原文地址:https://www.cnblogs.com/dachenzi/p/6595910.html
Copyright © 2011-2022 走看看