首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自定义Python Charmap Codec

自定义Python Charmap Codec
EN

Stack Overflow用户
提问于 2016-12-19 20:46:50
回答 1查看 1.4K关注 0票数 3

我正在尝试编写一个定制的Python编解码器。下面是一个简短的例子:

代码语言:javascript
复制
import codecs

class TestCodec(codecs.Codec):
    def encode(self, input_, errors='strict'):
        return codecs.charmap_encode(input_, errors, {
            'a': 0x01,
            'b': 0x02,
            'c': 0x03,
        })

    def decode(self, input_, errors='strict'):
        return codecs.charmap_decode(input_, errors, {
            0x01: 'a',
            0x02: 'b',
            0x03: 'c',
        })

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

codecs.register(lookup)
print(b'\x01\x02\x03'.decode('test'))
print('abc'.encode('test'))

解码工作,但编码抛出异常:

代码语言:javascript
复制
$ python3 codectest.py
abc
Traceback (most recent call last):
  File "codectest.py", line 29, in <module>
    print('abc'.encode('test'))
  File "codectest.py", line 8, in encode
    'c': 0x03,
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-2:
character maps to <undefined>

对如何正确使用charmap_encode有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-21 02:22:23

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

还有另一组编码(所谓的charmap编码),它们选择所有Unicode代码点的不同子集,以及如何将这些代码点映射到字节0x0-0xff。要了解这是如何实现的,只需打开encodings/cp1252.py (这是一种主要在Windows上使用的编码)。有一个包含256个字符的字符串常量,可以显示哪个字符被映射到哪个字节值。

请接受提示,查看编码/cp1252.py,并查看以下代码:

代码语言:javascript
复制
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))

输出:

代码语言:javascript
复制
{97: 1, 122: 0, 99: 3, 98: 2}
abc
b'\x01\x02\x03'
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41230733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档