JavaScript TextEncoder / TextDecoder equivalent in python



我想获得相同的结果,我们通过使用javascript上的TextEncoder和TextDecoder,但找不到真正的代码解决方案,我发现的解决方案不给我真正的相同的结果。

exp:

const textencoder = new TextEncoder();
console.log(textencoder.encode('$'));
//[36]
const textdecoder = TextDecoder();
console.log(textdecoder.decode(new Uint8Array([36]));
// $

经过多次尝试和搜索,我从一个朋友那里得到了解决方案,我决定与你分享,也许有一天有人需要它;

class TextEncoder():
    def __init__(self):
        pass
    
    def encode(self, text):
        """
        exp:
            >>> textencoder = TextEncoder()
            >>> textencoder.encode('$')
            >>> [36]
        """
        if isinstance(text, str):
            encoded_text = text.encode('utf-8')
            byte_array = bytearray(encoded_text)
            return list(byte_array)
        else:
            raise TypeError(f'Expecting a str but got {type(text)}')
class TextDecoder():
    def __init__(self):
        pass
    
    def decode(self, array):
        """
        exp:
            >>> textdecoder = TextDecoder()
            >>> textdecoder.decode([36])
            >>> $
        """
        if isinstance(array, list):
            return bytearray(array).decode('utf-8')
        elif isinstance(array, bytearray):
            return array.decode('utf-8')
        else:
            raise TypeError(f'expecting a list or bytearray got: {type(array)}')

最新更新