# -*- coding:utf-8 -*-
import sys,os
txta = open('a.txt','r')
str = ''
for line in txta:
str += line.strip().decode('utf-8')
txta.close()
for word in str:
print word.encode('utf-8')
直接输出,是会乱码的,得先解码,再编码。
参考网址:http://blog.csdn.net/devil_2009/article/details/39526713
首先要明白的是,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编码