Python3替换了ord()和chr()


for i in word:
c = ord(i) - int(key)
if c < 97:
c = c + 26
b = chr(c)
text += b

有没有其他方法可以在没有ord((和chr((的情况下替换它?

非常感谢!

这是一个使用numpy模块加上UTF-32编码/解码的代码。对于大数据,此代码将非常快速,并且不需要Python循环。

CCD_ 1模块使用CCD_。如果您需要没有numpy的解决方案,使用纯Python,并且运行速度不是问题,请告诉我,我会重写,但在纯Python中,代码在大数据上的工作速度会慢得多。

您也可以在这里在线运行此代码。

# Needs: python -m pip install numpy
import numpy as np
word = 'Duck'
key = 1
a = np.frombuffer(word.encode('utf-32-le'), dtype = np.int32)
a = a - key
a[a < 97] += 26
text = a.tobytes().decode('utf-32-le')
print(text)

类似的较慢的下一个解决方案,但没有numpy,只使用标准Python的内置模块struct。您也可以在线运行下一个代码。

import struct
word = 'Duck'
key = 1
text = ''
for i in word:
c = struct.unpack('<I', i.encode('utf-32-le'))[0] - int(key)
if c < 97:
c = c + 26
b = struct.pack('<I', c).decode('utf-32-le')
text += b

print(text)

下面的另一个解决方案不使用任何模块。在线运行下一个代码。

word = 'Duck'
key = 1
text = ''
for i in word:
c = int(i.encode('utf-32-be').hex(), 16) - int(key)
if c < 97:
c = c + 26
b = bytes.fromhex(hex(c)[2:].zfill(8)).decode('utf-32-be')
text += b

print(text)

如果文本符号仅来自ASCII集,则代码可以进一步简化(在线运行此代码(:

word = 'Duck'
key = 1
text = ''
for i in word:
c = i.encode('ascii')[0] - int(key)
if c < 97:
c = c + 26
b = bytes((c,)).decode('ascii')
text += b

print(text)

对于ASCII字符的情况,还有一个解决方案,使用两个表(在线运行此代码(

word = 'Duck'
key = 1
tmp = [(c, i) for i, c in enumerate(bytes(range(128)).decode('ascii'))]
c2i = dict(tmp)
i2c = [e[0] for e in tmp]
text = ''
for i in word:
c = c2i[i] - int(key)
if c < 97:
c = c + 26
b = i2c[c]
text += b

print(text)

通过替换下一行(在线运行此代码(,可以将以前的代码从ASCII扩展到更宽的字符集(例如16位(:

tmp = [(bytes.fromhex(hex(i)[2:].zfill(8)).decode('utf-32-be', 'replace'), i) for i in range(1 << 16)]

最新更新