如何在Python中将每个字符转换为它前面的字符并保持原始顺序?

2024-06-11 08:59:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有问题,我想不出解决的办法

注意:我不允许在我的代码中使用import

代码如下:

def decode(in_file, out_file): try: s = "" chr_nums = [] splitlst = [] lines = [] lst = [] f = open('q4.txt','r') for line in f: lines = line.split() for i in range(len(lines)): b = str(lines[i]) for l in b: chr_nums = chr(ord(l) - 1) for a in chr_nums: c =' '.join(a) print c except IOError: print "Cant decipher' {"+in_file+"} 'due to an IO Error." f.close()

此代码的目标是将每个单词中的每个字母替换为前面的字母。 i、 e:a变为z,依此类推

代码必须更改包含此类文本的文件:

Uif Xiffmt po uif cvt hp spvoe boe spvoe Uif Xiffmt po uif cvt hp spvoe boe spvoe

对这个结果:

The Wheels on the bus go round and round The Wheels on the bus go round and round

这是我的for循环在out\u文件中打印的内容:

T h e W h e e l s o n t h e b u s g o r o u n d a n d r o u n dT h e W h e e l s o n t h e b u s g o r o u n d a n d r o u n d

如何得到示例中显示的结果? 如何重新加入角色以形成原始顺序

注2:我确实尝试过使用join,但也没有成功地使用它

注3:代码获取的文件不一定包含同一个句子两次


Tags: 文件代码infor字母lineoutfile
2条回答

使用前面提到的if/else in Python's list comprehension

示例代码是

f = open('q4.txt','r')
for line in f:
    lst = list(line)
    lst2 = [chr(ord(x) - 1)  if x != ' ' else ' ' for x in lst]
    print("".join(lst2))

我得到了以下结果

The Wheels on the bus go round and round    
The Wheels on the bus go round and round
[Finished in 0.1s]

除了弗朗西斯王子的代码,这里还有一个采用您的代码风格的解决方案:

def decode(foo):
    final_string = ""
    f = foo
    for line in f:
        lines = line.split()
        for i in range(len(lines)):
            b = str(lines[i])
            for l in b:
                chr_nums = chr(ord(l) - 1)
                final_string += chr_nums
            final_string += " "
        final_string += "\n" # new line
    return(final_string)

secret_text = ["Uif Xiffmt po uif cvt hp spvoe boe spvoe", 
               "Uif Xiffmt po uif cvt hp spvoe boe spvoe"]

print(decode(foo=secret_text))

请注意,“try”后面的前五行是如何完全不需要的。它们没有影响。剩下的只是在适当的时候设置空格和换行符

相关问题 更多 >