zoukankan      html  css  js  c++  java
  • 如何调整字符串的文本格式?

    需求:
    某软件的Log文件,其中的日期格式为'yyyy-mm-dd':
    .....
    2016-05-23 10:59:26 status upacked python3-pip.all
    2016-05-23 10:59:26 status half-configured python3-all
    2016-05-23 10:59:26 status installed python3-pip.all
    2016-05-23 10:59:26 configure python3-wheel:all 0.24.0-1
    .....
    我们想把其中日期格式改为美国日期的格式’mm/dd/yyyy‘
    '2016-05-23 => 05/23/2016',应如何处理?

    思路:
    使用正则表达式re.sub()方法做字符串替换,利用正则表达式的捕获组,捕获每个部分内容,在替换字符串中调整各个捕获组的顺序。

    代码:
    py文件:

    mport re
    
    f = open('shizhandpdk.log')
    
    log = f.read()
    
    # 利用正则表达式的捕获组进行替换。
    ret = re.sub('(d{4})-(d{2})-(d{2})',r'3/2/1',log)
    
    
    #完成写入
    open('shizhandpdk.log','a').write('
    '+ret)
    
    open('shizhandpdk.log','a').close()
    
    print(ret)
    
    # 下面给捕获组取名,更直观一点也是可以的。
    # ret2 = re.sub('(?P<year>d{4})-(?P<month>d{2})-(?P<day>d{2})',r'g<day>/g<month>/g<year>',log)
    
    # print(ret2)
    

    dpdk.log:

    2016-05-23 10:59:26 status upacked python3-pip.all
    2016-05-23 10:59:26 status half-configured python3-all
    2016-05-23 10:59:26 status installed python3-pip.all
    2016-05-23 10:59:26 configure python3-wheel:all 0.24.0-1
    
  • 相关阅读:
    闭包函数+装饰器(第十一天)
    函数初接触2
    函数初接触
    第八天
    第八天
    第七天
    day4—day6作业(补发)
    第六天
    第五天
    python基础学习-常用模块的使用(扩展补充,高级使用)(三)
  • 原文地址:https://www.cnblogs.com/Richardo-M-Q/p/13284079.html
Copyright © 2011-2022 走看看