• 编码和解码


    '''str是以字节表示的文本,unicode是以字符表示的文本。
    您可以将文本从字节解码为Unicode,并使用某种编码将Unicode编码为字节。
    即:'''
    #str - --------> str(Unicode) - --------> str
    # encode:编码,编程不可识别的unicode
    # decode:解码, 恢复成字符串和中文等
    def test1():
    
        u = '中文'  # 指定字符串类型对象u
        str1 = u.encode('gb2312')  # 以gb2312编码对u进行编码,获得bytes类型对象
        print(str1)  #str1:<class 'bytes'>
        #>>>b'xd6xd0xcexc4'
        str2 = u.encode('gbk')  # 以gbk编码对u进行编码,获得bytes类型对象
        print(str2)
        #>>>b'xd6xd0xcexc4'
        str3 = u.encode('utf-8')  # 以utf-8编码对u进行编码,获得bytes类型对象
        print(str3)
        #>>>b'xe4xb8xadxe6x96x87'
        u1 = str1.decode('gb2312')  # 以gb2312编码对字符串str进行解码,获得字符串类型对象
        print(u1)
        #>>>中文
        #u2 = str1.decode('utf-8')  # 报错,因为str1是gb2312编码的
        u3 = str3.decode('utf-8')   #str3是utf-8编的马,所以可以解
        print(u3)
        #>>>中文
        #print('ddd'.decode('utf-8')) #报错,已经是字符串了,还解什么码, 但是可以编码 如encode('utf-8')
        print(type(str1))
        #>>><class 'bytes'>
        print(type(u3))
        #>>><class 'str'>
    
    if __name__=='__main__':
        test1()
    

      

    读取文件,发现数据文件的编码是gb2312,所以读取一行内容后需要转为unicode然后再转为utf8:

    line = line.decode('gbk').encode('utf-8')

    (奇怪的是用’gb2312’就不行)

    unicode是中转站



  • 相关阅读:
    文件搜索和图像裁剪
    Mat的复制
    map
    substr
    cin,scanf
    strstr
    Applying vector median filter on RGB image based on matlab
    sobel算子的一些细节
    matlab 有趣小细节
    高斯混合模型(GMM)
  • 原文地址:https://www.cnblogs.com/lxgbky/p/12427092.html
Copyright © 2020-2023  润新知