【问题标题】:how to change the character to the one before it using ascii如何使用ascii将字符更改为之前的字符
【发布时间】:2018-12-06 18:42:08
【问题描述】:

我的代码有问题。 它需要将每个字符更改为之前的字符。 这里的问题是文件:

uif xiffmt po uif cvt hp spvoe boe spvoe
uif xiffmt po uif cvt hp spvoe boe spvoe

它需要返回:

the wheels on the bus goes round and round
the wheels on the bus goes round and round

但它会在一行中返回它们:

the wheels on the bus goes round and round  the wheels on the bus goes round and round

我该如何解决这个问题?

def decode(in_file, out_file):
    try:
        f = open(in_file, 'r')
        for line in f:
            lst = list(line)
            lst2 = [chr(ord(x) - 1)  if x != ' ' else ' ' for x in lst]
            a = "".join(lst2) 
            with open('out_file.txt','a') as f2:
                f2.write(a)

    except IOError:
        print "Cant decipher' {"+in_file+"} 'due to an IO Error."
        f.close()
    finally:
        if f!=None:
            f.close()
            f2.close()
print decode( 'q4.txt', 'out_file.txt')

【问题讨论】:

  • 换行符不知何故丢失了。您需要防止这种情况发生,或者在完成一行后将其添加回来。

标签: python-2.7 file ascii caesar-cipher


【解决方案1】:

编辑:我刚刚意识到我的(和你的;))错误,真正的答案如下

当您更改承租人时,您也为不可打印的承租人执行此操作 - 那些 ascii 代码 \n,代码编号 10,它被替换为制表符 -代码 9.
解决方法是简单地跳过使用此类代码号更改所有内容:

 lst2 = [chr(ord(x) - 1)  if ord(x)>32 else x for x in lst]

旧答案,没有解决实际问题。

write() 方法不会自动添加换行符 - 它会写入任何变量值,然后完成。

所以你应该自己附加一个:

        with open('out_file.txt','a') as f2:
            f2.write(a + '\n')

或者,将所有修改的行存储在列表变量中,使用writelines() 方法转储其内容 - 它用换行符分隔每个列表成员。

【讨论】:

    猜你喜欢
    • 2012-01-15
    • 1970-01-01
    • 2014-07-11
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多