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()編碼成指定格式。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章