gpt4 book ai didi

python - 如何正确创建自定义文本编解码器?

转载 作者:太空狗 更新时间:2023-10-29 17:19:38 30 4
gpt4 key购买 nike

我正在挖掘一些包含(除其他外)文本的旧二进制文件。他们的文本出于原因经常使用自定义字符编码,我希望能够阅读和重写它们。

在我看来,执行此操作的适当方法是使用 standard codecs library 创建自定义编解码器.不幸的是,它的文档既庞大又完全没有示例。 Google 出现了一些,但仅适用于 python2,而我使用的是 3。

我正在寻找一个关于如何使用编解码器库实现自定义字符编码的最小示例。

最佳答案

你要求最小!

  • 编写一个编码函数和一个解码函数。
  • 编写一个“搜索函数”,返回由上述编码器和解码器构建的 CodecInfo 对象。
  • 使用 codec.register 注册一个返回上述 CodecInfo 对象的函数。

下面是一个将小写字母 a-z 依次转换为 0-25 的例子。

import codecs
import string

from typing import Tuple

# prepare map from numbers to letters
_encode_table = {str(number): bytes(letter, 'ascii') for number, letter in enumerate(string.ascii_lowercase)}

# prepare inverse map
_decode_table = {ord(v): k for k, v in _encode_table.items()}


def custom_encode(text: str) -> Tuple[bytes, int]:
# example encoder that converts ints to letters
# see https://docs.python.org/3/library/codecs.html#codecs.Codec.encode
return b''.join(_encode_table[x] for x in text), len(text)


def custom_decode(binary: bytes) -> Tuple[str, int]:
# example decoder that converts letters to ints
# see https://docs.python.org/3/library/codecs.html#codecs.Codec.decode
return ''.join(_decode_table[x] for x in binary), len(binary)


def custom_search_function(encoding_name):
return codecs.CodecInfo(custom_encode, custom_decode, name='Reasons')


def main():

# register your custom codec
# note that CodecInfo.name is used later
codecs.register(custom_search_function)

binary = b'abcdefg'
# decode letters to numbers
text = codecs.decode(binary, encoding='Reasons')
print(text)
# encode numbers to letters
binary2 = codecs.encode(text, encoding='Reasons')
print(binary2)
# encode(decode(...)) should be an identity function
assert binary == binary2

if __name__ == '__main__':
main()

运行这个打印

$ python codec_example.py
0123456
b'abcdefg'

有关 Codec 接口(interface)的详细信息,请参阅 https://docs.python.org/3/library/codecs.html#codec-objects。特别是解码函数

... decodes the object input and returns a tuple (output object, length consumed).

而编码函数

... encodes the object input and returns a tuple (output object, length consumed).

请注意,您还应该担心处理流、增量编码/解码以及错误处理。更完整的例子可以引用@krs013提到的hexlify codec


附言除了 codec.decode,您还可以使用 codec.open(..., encoding='Reasons')

关于python - 如何正确创建自定义文本编解码器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38777818/

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