您的位置:首页 > 编程语言 > Python开发

Python 万恶的乱码

2015-07-09 15:15 656 查看
这两天在做从txt中读取中文展示在界面的内容,结果,万恶的编码问题把我弄得头都大了,我之前的做法是引用chardet的detect方法获取编码,然后用Unicode解码后,再用encode编码,结果还是乱码,后来,经同事指点,才知道,原来输入到基于Python的gui中,只需要Python内部的Unicode就行了,具体做法如下:

if len(post_seq) > 0:
        for i in range(len(post_seq)):
            str = post_seq[i].split("|")
            str[1] = str[1].decode("GBK")#这是关键啊
            str[0] = str[0].decode("GBK")
            dict[str[0]] = str[1]
            print str[1]
        print len(dict)
        return dict


另外给下这几天弄出的,转换编码的吧

#获取编码
    enc = chardet.detect(seq)['encoding']#str类型的才可使用该函数,返回值是字典类型
    print enc
    after_enc = unicode(seq, enc)#转为Unicode
    print chardet.detect(after_enc)
    os.popen("iconv.exe -f %s -t gbk -c record.txt > record_encode.txt" % enc)#使用编码转换器转换编码,以gbk形式写进record_encode.txt文件
    shutil.copy("record_encode.txt", "record.txt")#复制
    print open(current_dir, "r").read()


有时候转换编码不行,就当学习下吧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: