python处理中文字符

简介:

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



#!/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......'  











本文转自 chengxuyonghu 51CTO博客,原文链接:http://blog.51cto.com/6226001001/1898592,如需转载请自行联系原作者
目录
相关文章
|
3月前
|
存储 算法 Python
python 无重复字符的最长子串 多种解法
python 无重复字符的最长子串 多种解法
|
7月前
|
Python Windows
用 Python 将神龙大侠搞怪 GIF 转为字符动画
用 Python 将神龙大侠搞怪 GIF 转为字符动画
59 0
用 Python 将神龙大侠搞怪 GIF 转为字符动画
|
9月前
|
自然语言处理 Python
【Python学习笔记】使用jieba分词,输出字符长度大于2词组成的列表(计算机二级题目)
【Python学习笔记】使用jieba分词,输出字符长度大于2词组成的列表(计算机二级题目)
|
1月前
|
索引 Python
Python 超高频常见字符操作【建议收藏】
Python 超高频常见字符操作【建议收藏】
|
2月前
|
Python
在Python中实现图片转字符画灰度处理或灰色量化
在Python中实现图片转字符画灰度处理或灰色量化
25 1
|
2月前
|
计算机视觉 Python
在Python中实现图片转字符画打开图片
在Python中实现图片转字符画打开图片
10 1
|
2月前
|
Python
在Python中实现图片转字符画导入所需库
在Python中实现图片转字符画导入所需库
9 1
|
2月前
|
存储 算法 计算机视觉
在Python中实现图片转字符画
在Python中实现图片转字符画
14 1
|
3月前
|
算法 Python Java
Python每日一练(20230426) 删除重复字符、颜色分类、计算圆周率
Python每日一练(20230426) 删除重复字符、颜色分类、计算圆周率
39 0
Python每日一练(20230426) 删除重复字符、颜色分类、计算圆周率
|
7月前
|
Python
Python转义字符与原字符
Python转义字符与原字符
33 1

热门文章

最新文章