zoukankan      html  css  js  c++  java
  • 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
    st.txt'
    
    #----------------------------------------------------------------------
    def find_all_files(path):
        '''
        '''
        print '
    
    '
        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!', '	', 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') + '
    '
        
        fp = open(rstPath, 'w')
        fp.write(rst)
        fp.close()
        
        print '
    Run 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()编码成指定格式。


  • 相关阅读:
    Yield Usage Understanding
    Deadclock on calling async methond
    How to generate file name according to datetime in bat command
    Run Unit API Testing Which Was Distributed To Multiple Test Agents
    druid的关键参数+数据库连接池运行原理
    修改idea打开新窗口的默认配置
    spring boot -thymeleaf-url
    @pathvariable和@RequestParam的区别
    spring boot -thymeleaf-域对象操作
    spring boot -thymeleaf-遍历list和map
  • 原文地址:https://www.cnblogs.com/Harry-Lord/p/4002844.html
Copyright © 2011-2022 走看看