2016-12-19 4 views
1

私はカスタムPythonコーデックを作成しようとしています。ここでは簡単な例です:カスタムPython Charmapコーデック

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を適切に使用する方法?

答えて

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

見て、エンコード/ 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' 
+0

ありがとう!それが助けになりました。 –

+0

@DaniloBargenうれしいです。 –

関連する問題