在Python解码环中循环遍历字符串中的每个字符
我正在尝试用Python制作一个简单的解码器。
举个例子:
a=b, `b=c, c=d, etc.
我希望这个脚本能够接收一个编码过的信息,然后输出解码后的信息。
比如,我输入 "ifmmp"
,它就会输出 "hello"
。
我在想,我需要把所有的字符分开,然后逐个循环处理,改变它们的 chr()
或 ord()
值。
在Python中似乎没有相关的文档。
4 个回答
3
from string import maketrans
table = maketrans('abcdefghijklmnopqrstuvwxyz/','zabcdefghijklmnopqrstuvwxy ')
for x in ('pdfbo','qipophsbqi','cmvf/nppo/jo/b/sfe/tlz'):
print x,' -> ',x.translate(table)
结果
pdfbo -> ocean
qipophsbqi -> phonograph
cmvf/nppo/jo/b/sfe/tlz -> blue moon in a red sky
.
编辑
我重新写了Joachim的算法(函数better()),并且写了我自己的解决方案,没有使用maketrans()(yop()):
s = '{ifmmp}\t\tcmvf-nppo \n SUNNY ~ ajhabh 14568'
def bof(s):
new_s = ''
for c in s:
n = ord(c)
n = n - 1
if n < ord('a'):
# 'a' -> 'z'
n = ord('z')
new_s += chr(n)
return new_s
def better(s):
li = []
for c in s:
n = ord(c)-1
if n == 96:
li.append('z')
elif 96<n<122:
li.append(chr(n))
else:
li.append(c)
return ''.join(li)
def yop(s):
gen = ((c,ord(c)-1) for c in s)
return ''.join('z' if y==96 else chr(y) if 96<y<122 else x for x,y in gen)
def better_yop(s):
def gen(h):
for c in h:
n = ord(c)-1
if n == 96:
yield 'z'
elif 96<n<122:
yield chr(n)
else:
yield c
return ''.join(gen(s))
for truc in (s,bof(s),better(s),yop(s),better_yop(s)):
print '%r\n%s\n' % (truc,truc)
结果
'{ifmmp}\t\tcmvf-nppo \n SUNNY ~ ajhabh 14568'
{ifmmp} cmvf-nppo
SUNNY ~ ajhabh 14568
'zhello|zzbluezmoonzzzzzzzzz}zzigzagzzzzzz'
zhello|zzbluezmoonzzzzzzzzz}zzigzagzzzzzz
'{hello}\t\tblue-moon \n SUNNY ~ zigzag 14568'
{hello} blue-moon
SUNNY ~ zigzag 14568
'{hello}\t\tblue-moon \n SUNNY ~ zigzag 14568'
{hello} blue-moon
SUNNY ~ zigzag 14568
'{hello}\t\tblue-moon \n SUNNY ~ zigzag 14568'
{hello} blue-moon
SUNNY ~ zigzag 14568
不过,我的函数yop()比better()要慢
.
编辑
现在函数better_yop()的速度和better()差不多
不过,better()似乎还是比better_yop()稍微快一点。因为better()也更简单,所以better()是最好的选择。
4
别再纠结循环了,尽量使用Python自带的功能:
from string import maketrans, translate, ascii_lowercase
import functools
translation = maketrans(ascii_lowercase, ascii_lowercase[-1]+ascii_lowercase[:-1])
decipher = functools.partial(string.translate, table=translation)
print(decipher("ifmmp")) # 'hello'
14
这样写怎么样:
s = 'ifmmp'
new_s = ''
for c in s:
n = ord(c)
n = n - 1
if n < ord('a'):
# 'a' -> 'z'
n = ord('z')
new_s += chr(n)
# print('new_s = %r' % new_s) -> new_s = 'hello'
当然,这个只处理小写字母,不包括大写字母。