gpt4 book ai didi

python - 自定义 Python 字符映射编解码器

转载 作者:太空宇宙 更新时间:2023-11-04 00:42:35 25 4
gpt4 key购买 nike

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

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

解码有效,但编码抛出异常:

$ 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 有什么想法吗?

最佳答案

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

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.

根据提示查看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 - 自定义 Python 字符映射编解码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41230733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com