一、题目分析
文件中有大量的无用信息,若果逐一排除会比较麻烦棘手。
所以可以反其道而行
所有的英文单词都是前面跟数字,这样只需要判断第一个区域是不是数字就行
然后分割字符串后面的单词放入字典
解密用的是pta的原题,进行了部分改动
可以参考这个https://blog.youkuaiyun.com/weixin_45759918/article/details/124362645#62__10__58
二、参考答案
# 读取并加工文件内容
# 输入:fileName --->> 文件名
# 输出:dictionary --->> 加工后的列表
def readFile(fileName):
strs = ""
# 这样写读取完文件程序会自动关闭文件,不用手动关闭
with open(fileName, 'r', encoding="UTF-8", newline=None) as file:
# 逐行读取,存放为list
lines = file.readlines()
# lines下标
x = 0
# 需要删除的下标
delNumber=[]
# 粗加工,去除换行符
for i in lines:
lines[x] = i.strip()
x +=1
# 加工后列表
dictionary = []
# 根据文件格式,数字+空格(1-2个)+英文单词
for i in lines:
isNum = i.split(" ")[0].isdigit()
# 若开头是数字,则去数字后的单词
if isNum:
Word = i.split(" ")[1]
# 若有多个空格导致下标为1时是空格,则延续到下标为2的位置
if Word == "":
Word = i.split(" ")[2]
dictionary.append(Word)
print(f"共计{len(dictionary)}个单词")
return dictionary
def Crack(text,fileName):
# 分割字符串
text = text.split(' ')
# 判断末尾是否有标点
flag = True
# 若有标点则存放起来
if not text[-1].isalpha():
flag = False
oldword = list(text[-1])
restructuring = ""
# 标点存放字符串
symbol = ""
for i in oldword:
if i.isalpha():
restructuring = restructuring + i
else:
symbol = i
text[-1] = restructuring
# 提供的单词字典
EnglishWord = readFile(fileName)
# 解密后句子
for x in range(1, 26):
newList = []
for i in text:
# 凯撒解密
words = Decrypt(i, x)
# 将单词组装到解密句子
newList.append(words)
# 统计句子中与字典中相同个数
count = 0
# 在字典中循环寻找对应解密的单词,如果对应则数目加一
for k in EnglishWord:
for m in newList:
if k == m.lower():
count += 1
# 判断正确比例
numbers = count / len(newList)
# 正确比例大于60%则输出,原加密句式中有标点则补上
if numbers >= 0.5:
a = " ".join(newList)
if not flag:
a = a + symbol
return a
# 可以使用下面的函数,进行凯撒解密
def Decrypt(text, numToMove):
afterText = ""
for p in text:
if ord("a") <= ord(p) <= ord("z"):
afterText += chr(ord("z")-(ord('z')-ord(p)+numToMove)%26)
elif ord("A") <= ord(p) <= ord("Z"):
afterText += chr(ord("Z")-(ord('Z')-ord(p)+numToMove)%26)
else:
afterText += p
return afterText
fileName = input("请输入字典文件名:")
text = input("请输入加密的语句:")
org = Crack(text,fileName)
print(org)