编码方案是从每个字符的ASCII值中减去2

问题描述 投票:0回答:2

基本上,我有一个需要解码的文件。我是编码新手,不确定要怎么做。

目前我有此代码:

infile = open('encoded_2.txt')

for line in infile:
    line = line.strip()
    print(line,end=' ')

我得到这个:

Ml rfc rp_gj rm Mpceml

但是我希望它是:

On the trail to Oregon
python character-encoding ascii
2个回答
0
投票

一个人可以使用ord(将字符转换为ASCII码)和chr(将字符转换为ASCII码)功能:

line = "Ml rfc rp_gj rm Mpceml"
newline =""
for i in range(len(line)):
    newline += chr(ord(line[i])+2)
print(newline)

输出:

On"the"trail"to"Oregon

空格字符也正在转换。

显然空间未编码在原始文件中。因此,可以将其排除在解码之外:

line = "Ml rfc rp_gj rm Mpceml"
newline =""
for i in range(len(line)):
    if line[i] == ' ':
        newline += ' '
    else: 
        newline += chr(ord(line[i])+2)
print(newline)

输出:

On the trail to Oregon

如果条件可以放在一行中:

for i in range(len(line)):
    newline += ' ' if line[i] == ' ' else chr(ord(line[i])+2)

0
投票

这对我有用:

>>> text = 'Ml rfc rp_gj rm Mpceml'
>>> ''.join(chr(ord(t)+2) if t != ' ' else t for t in text)
'On the trail to Oregon'
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.