我可以在维基百科上找到 uuencode 字符映射。python有没有办法遍历这个列表?
for x in [builtin_uuencode_mappings]:
print(x)
我想专注于特殊字符,例如“!@#$”等。
Python 已经内置了对 uuencoded 消息的编码和解码的支持。
from codecs import encode # decode also works
print(encode("my message", 'uu'))
# -> 'begin 666 <data>\n*;7D@;65S<V%G90 \n \nend\n'
在内部,python 使用binascii
包逐行编码或解码消息。我们可以使用它来编码单个字节甚至所有字节range(64)
(因为 uuencoding 将 6bit 转换为 ascii 字符:)2**6 == 64
。
为了生成所有必要的位模式,我们可以数到 64 并将结果左移 2 位。这样,最高 6 位从 0 计数到 64。然后只需将其转换为 python bytes
,对它们进行 uuencode 并提取实际字符。
在python2
from binascii import b2a_uu
for byte in range(64):
pattern = chr(byte << 2) # str and bytes are identical in python2
encoded = b2a_uu(pattern)
character = encoded[1] # encoded[0] is the character count in that line
print "{:2} -> {!r}".format(byte, character)
在 python3 中,第一部分有点难看。
from binascii import b2a_uu
for byte in range(64):
pattern = bytes([byte << 2]) # chr().encode() will not work!
encoded = b2a_uu(pattern)
character = chr(encoded[1])
print(f"{byte:2} -> {character!r}")
感谢 Mark Ransom,他解释了为什么移位确实有效。