问题描述
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循环。
numpy
模块可以使用python -m pip install numpy
轻松安装。如果您需要不带numpy的解决方案,请使用纯Python,并且运行速度不是问题,请告诉我,我会重写,但是在纯Python代码中,大数据的运行速度会慢得多。
您也可以run this code online here。
# 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
。您也可以run next code online。
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)
下面的另一个解决方案,不使用任何模块。 Run next code online。
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组,则可以进一步简化代码(run this code online):
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)
使用两个表(run this code online)的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)
通过替换下一行(run this code online),可以将先前的代码从ASCII扩展到更宽的字符集(例如16位):
tmp = [(bytes.fromhex(hex(i)[2:].zfill(8)).decode('utf-32-be','replace'),i) for i in range(1 << 16)]