完美解决 python2.7 unicode 中文处理问题

2025-09-26 02:22:41

1、建立.py 文件

文件头:

# coding=utf-8

代表 python 使用utf-8作为默认字符集。

2、定义函数用于转换unicode字符串, 该函数专门用于解决unicode双字节混合编码的。

# 利用 repr 解决 UNICODE 双字节混合编码

def convertToUX(content):

        tmp = ""

        for cr in content:

                if (cr=="u"强诉仗 or cr=="'"):

                        tmp = tmp + cr

                        continue

                tmp = tmp + repr(cr).replace("u'", "").replace("'","")

        return tmp.decode("unicode_escape").encode("utf-8")

3、完整代码验证:

# coding=UTF-8

# 利用 repr 解决 UNICODE 双字节混合编码

def convertToUX(content):

        tmp = ""

        for cr in content:

                if (cr=="u" or cr=="'"):

                        tmp = tmp + cr

                        continue

                tmp = tmp + repr(cr).replace("u'", "").replace("'","")

        return tmp.decode("unicode_escape").encode("utf-8")

test_str =  u"Hello,World, 世界, 你好, \u4f60\u597d"

print test_str #直接 print 到屏幕没有任何问题,但进行字符串处理,如写入文件则会字符集处理报错。

#经过转换后保存到文件

tmpfile = open('/root/test.log', 'w')

try:

        tmp_test_str = convertToUX(test_str)

        tmpfile.write(tmp_test_str)

        print "经过转换后保存成功! "

except Exception, ex:

        print "转换保泥矿存报错!"

        print str(ex)

finally:

        tmpfile.close()

#直接使用保存到文件

#直接保存一定会失败,我们就是为了解决这种混合编码的问题。

tmpfile1 = open('/root/test1.log','w')

try:

        print test_str

        tmpfile1.write(test_str)

     仗争   print "直接保存成功!"

except Exception, ex:

        print "直接保存失败:"

        print str(ex)

finally:

        tmpfile1.close()

4、当我们退出vim在linux ,执行验证 python test.py 会发现

输出:

Hello,World, 世界, 你好, 你好

经过转换后保存成功! 

Hello,World, 世界, 你好, 你好

直接保存失败:

'ascii' codec can't encode characters in position 13-14: ordinal not in range(128)

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢