码迷,mamicode.com
首页 > 编程语言 > 详细

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

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

标签:python   正则表达式   ascii   os   

正则表达式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()找到的结果替换

标签:python   正则表达式   ascii   os   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!