python处理中文字符的一点经验

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys, os
import md5

destPath = r'h:\路径A\测试'
srcPath = r'h:\路径B\测试'
rstPath = r'h:\路径C\rst.txt'

#----------------------------------------------------------------------
def find_all_files(path):
    '''
    '''
    print '\r\r'
    files = os.listdir(path.decode('utf8'))
    fileslist = []
    for ff in files:
        ffPath = path + '\\' + ff
        print ffPath,
        if os.path.isfile(ffPath):
            fileslist.append(ffPath)
            print 'file'
        elif os.path.isdir(ffPath):
            print 'dir'
            fileslist += find_all_files(ffPath)
        else:
            print 'parse error!', '\t', ffPath
    return fileslist

#----------------------------------------------------------------------
def md5_list(path):
    '''
    '''
    filesList = find_all_files(path)
    filesMd5 = {}
    for ff in filesList:
        try:
            fp = open(ff, 'rb')
            m = md5.md5()
            strRead = ""
            while True:
                strRead = fp.read(8096)
                if not strRead:
                    break
                m.update(strRead)
            strMd5 = m.hexdigest()
            filesMd5[strMd5] = ff
            fp.close()
        except Exception, ex:
            print ex
            fp.close()
    
    return filesMd5

if __name__=='__main__':
    reload(sys)
    sys.setdefaultencoding('utf-8')
    print 'Begin.......'   

    srcFilesMd5 = md5_list(srcPath)
    destFilesMd5 = md5_list(destPath)
    
    rst = ''
    for key in srcFilesMd5.keys():
        if key not in destFilesMd5.keys():
            fileName = srcFilesMd5[key]
            rst = rst + fileName.encode('utf8') + '\r'
    
    fp = open(rstPath, 'w')
    fp.write(rst)
    fp.close()
    
    print '\nRun Over......'

      此脚本能根据文件内容,从一个文件夹下找出不重复于另一个文件夹下的文件,并把结果记录在rstPath里。
      编写该脚本过程中遇到最大问题竟然是路径中的中文问题。以前也遇到过中文问题,但是都没有彻底搞清楚,只是试探的用decode()或encode()去解决。这次总算了解个大概,并总结出了一点经验。
       首先要明白的是,python里面默认的字符串都是ASCII编码,是string类型,ASCII编码处理中文字符是会出问题的。python的内部编码格式是unicode,在字符串前加‘u’前缀也可直接声明unicode字符串,如 u'hello'就是unicode类型。
如果处理的字符串中出现非ascii码表示的字符,要想不出错,就得转成unicode编码了。具体的方法有:
decode(),将其他边编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码;
encode(),将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码;
unicode(),同decode(),将其他编码的字符串转换成unicode编码,如unicode(str3, 'gb2312'),表示将gb2312编码的字符串str3转换成unicode编码。
转码的时候一定要先搞明白字符串str是什么编码,然后decode成unicode,最后再encode成其他编码。
      另外,对一个unicode编码的字符串在进行解码会出错,所以在编码未知的情况下要先判断其编码方式是否为unicode,可以用isinstance(str, unicode)。
      不仅是中文,以后处理含非ascii编码的字符串时,都可以遵循以下步骤:
1、确定源字符的编码格式,假设是utf8;
2、使用unicode()或decode()转换成unicode编码,如str1.decode('utf8'),或者unicode(str1, 'utf8');
3、把处理后字符串用encode()编码成指定格式。


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值