- 英文文本文件加密
【问题描述】
现有一种英文文本文件加密方法。该方法设定的加密密钥为整数3,表示以加密前字符为起始位置,依据字母表中字母顺序,向后移动3个位置,得到加密后字符。例如,加密前字符“A”在加密后转换为“D”,加密前字符“Z”在加密后转换为“C”,依次类推。小写字母亦如此(参见下图),其它字符不变。用该方法对文件加密。例如:
加密前字符
M
E
e
t
m
e
a
t
加密后字符
P
H
h
w
p
h
d
W
【输入形式】
读取当前目录下的文件in.txt,该文件含有多行任意字符,也可能有空行。每个文本行最长不超过80个字符。(注意:程序中使用open()函数打开文件时,文件位置描述只写文件名和扩展名,比如open(“in.txt”,“r”))
in.txt
【输出形式】
对输入文件内容按上述方法进行加密后输出到当前目录下文件out.txt中。
【样例输入1】
in.txt文件内容如下:
c language is important.
WO AI BEIJING TIANANMEN.
YYH SZ DSZ DDSZ.
【样例输出1】
f odqjxdjh lv lpsruwdqw.
ZR DL EHLMLQJ WLDQDQPHQ.
BBK VC GVC GGVC.
【样例输入2】
in.txt文件内容如下:
Northwest A&F University is located in Yangling, Shaanxi, which is the birthplace of Chinese agricultural civilization and a national agricultural high-tech industry demonstration zone.
It is a key construction university directly under the Ministry of Education and the national “985 Project” and “211 Project”.
It was selected as one of the first national “world-class universities and first-class disciplines” construction universities.
In 2022, it was selected as a national second round of “Double First Class” construction universities, and two disciplines were selected as “Double First Class” construction disciplines.
【样例输出2】
Qruwkzhvw D&I Xqlyhuvlwb lv orfdwhg lq Bdqjolqj, Vkddqal, zklfk lv wkh eluwksodfh ri Fklqhvh djulfxowxudo flylolcdwlrq dqg d qdwlrqdo djulfxowxudo kljk-whfk lqgxvwub ghprqvwudwlrq crqh.
Lw lv d nhb frqvwuxfwlrq xqlyhuvlwb gluhfwob xqghu wkh Plqlvwub ri Hgxfdwlrq dqg wkh qdwlrqdo “985 Surmhfw” dqg “211 Surmhfw”.
Lw zdv vhohfwhg dv rqh ri wkh iluvw qdwlrqdo “zruog-fodvv xqlyhuvlwlhv dqg iluvw-fodvv glvflsolqhv” frqvwuxfwlrq xqlyhuvlwlhv.
Lq 2022, lw zdv vhohfwhg dv d qdwlrqdo vhfrqg urxqg ri “Grxeoh Iluvw Fodvv” frqvwuxfwlrq xqlyhuvlwlhv, dqg wzr glvflsolqhv zhuh vhohfwhg dv “Grxeoh Iluvw Fodvv” frqvwuxfwlrq glvflsolqhv.
【样例说明】
对输入文件的内容进行加密,并将结果输出到文件out.txt中。
def sc(c, e):
if c.isalpha():
a = ord('A') if c.isupper() else ord('a')
return chr((ord(c) - a + e) % 26 + a)
else:
return c
def et(text, e):
return ''.join(sc(c, e) for c in text)
e = 3
with open("in.txt", "r") as file:
lines = file.readlines()
with open("out.txt", "w") as file:
for line in lines:
el = et(line.strip(), e)
file.write(el + '\n')