自定义Python Charmap编解码器 [英] Custom Python Charmap Codec

查看:114
本文介绍了自定义Python Charmap编解码器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写自定义Python编解码器。这是一个简短的示例:

I'm trying to write a custom Python codec. Here's a short example:

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'))

解码有效,但编码会引发异常:

Decoding works, but encoding throws an exception:

$ 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

Any ideas how to use charmap_encode properly?

推荐答案

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


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

There’s another group of encodings (the so called charmap encodings) that choose a different subset of all Unicode code points and how these code points are mapped to the bytes 0x0-0xff. To see how this is done simply open e.g. encodings/cp1252.py (which is an encoding that is used primarily on Windows). There’s a string constant with 256 characters that shows you which character is mapped to which byte value.

提示一下编码/ cp1252.py,并检查以下代码:

take the hint to look at encodings/cp1252.py, and check out the following code:

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 Charmap编解码器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆