首页 > 编程语言 > 详细

python中re.findall()找到的结果替换

时间:2015-05-20 22:20:36      阅读:296      评论:0      收藏:0      [点我收藏+]

正则表达式re模块中用findall查找到的是ascii码,所以当比对替换时也需要对应的ascii码才能匹配成功。以下程序是查找文件夹下文件名中含有男、女的文件,并将男替换成1,将女替换成2的程序

# -*- coding: utf-8 -*-
 
import fnmatch
import os
import codecs
import re
import sys
 
def iterfindfiles(path, fnexp):
    for root, dirs, files in os.walk(path):
        for filename in fnmatch.filter(files, fnexp):
            yield os.path.join(root, filename)
 
def fiterFiles():
     
    path=raw_input("input dir:")
    filterfiletype=raw_input("input file filter type:")
 
    #quanjiao_2_banjiao(path)
 
    for filename in iterfindfiles(path,filterfiletype):
        SingerList=re.findall('\((..?)\)\.dat',filename)
        for SingerName in SingerList:
            if(SingerName=='\xc4\xd0'):
                SingerName='1'
                new_filename=re.sub('\((..?)\)\.dat','(1).dat',filename)
                print new_filename
                os.rename(filename,new_filename)
                #print SingerName
            elif(SingerName=='\xc5\xae'):
                SingerName='2'
                new_filename=re.sub('\((..?)\)\.dat','(2).dat',filename)
                print new_filename
                os.rename(filename,new_filename)
 
def main():
    fiterFiles()
 
 
if __name__ == "__main__":
    main()


python中re.findall()找到的结果替换

原文:http://blog.csdn.net/dannyoung/article/details/45875591

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!