Python正则表达式练习题

来源:互联网 发布:师范网络教育 编辑:程序博客网 时间:2024/06/11 16:37

题目来源:http://www.cnblogs.com/vamei/archive/2012/08/31/2661870.html

推荐博客园的一个学习Python的快速教程

http://www.cnblogs.com/vamei/archive/2012/09/13/2682778.html
练习题:

有一个文件,文件名为output_1981.10.21.txt 。下面使用Python: 读取文件名中的日期时间信息,并找出这一天是周几。将文件改名为output_YYYY-MM-DD-W.txt (YYYY:四位的年,MM:两位的月份,DD:两位的日,W:一位的周几,并假设周一为一周第一天)


import reimport timeimport datetimefilename = "output_1981.10.21.txt"m = re.search("output_(\d{4}.\d{2}.\d{2})", filename)searchResult = m.group(1)print ("matcht result: %s" % searchResult)dates = searchResult.split('.')for date in dates:    print dateyear = dates[0]month = dates[1]day = dates[2]xingqi = datetime.datetime(int(year), int(month), int(day)).strftime("%w")# replace to new filenametheReplacePart = '%s-%s-%s-%s' % (year,month,day,xingqi)print 'the new filename is: %s' % theReplacePartnewfileName = re.sub("\d{4}.\d{2}.\d{2}", theReplacePart, filename)print newfileName

最近在学习Python,这是我的解答,欢迎大家贴上自己的答案
原创粉丝点击