您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

自定义Python Charmap编解码器

自定义Python Charmap编解码器

查看https://docs.python.org/3/library/codecs.html#encodings-and- unicode(第三段):

还有另一组编码(所谓的charmap编码),它们选择所有Unicode代码点的不同子集,以及如何将这些代码点映射到字节0x0-0xff。要查看如何完成此操作,只需打开egencodings/cp1252.py(这是主要在Windows上使用的编码)。有一个包含256个字符的字符串常量,向您显示哪个字符映射到哪个字节值。

提示看encodings / cp1252.py,并查看以下代码

import codecs

class TestCodec(codecs.Codec):
    def encode(self, input_, errors='strict'):
        return codecs.charmap_encode(input_, errors, encoding_table)

    def decode(self, input_, errors='strict'):
        return codecs.charmap_decode(input_, errors, decoding_table)

def lookup(name):
    if name != 'test':
        return None
    return codecs.CodecInfo(
        name='test',
        encode=TestCodec().encode,
        decode=TestCodec().decode,
    )

decoding_table = (
    'z'
    'a'
    'b'
    'c'
)    
encoding_table=codecs.charmap_build(decoding_table)
codecs.register(lookup)

### --- following is test/debug code
print(ascii(encoding_table))

print(b'\x01\x02\x03'.decode('test'))
foo = 'abc'.encode('test')
print(ascii(foo))

输出

{97: 1, 122: 0, 99: 3, 98: 2}
abc
b'\x01\x02\x03'
python 2022/1/1 18:50:49 有369人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶