这是我第一次写博客,有不足之处,希望大家指出,谢谢!
这次的题目一共有三个难度,分别是简单,中等偏下,中等。对于一些刚刚入门的小伙伴来说,比较友好。废话不多说,直接进入正题。
【题目要求】:
实现以《三国演义》为密码本,对输入的中文文本进行加密和解密。至于加密方式,最简单的从0开始,一直往后,有多个字,就最多到多少。
【分析】:
1.知识背景:需要用到文件的读写操作,以及字典和集合的相关知识。
2思路:现将文件读取进来,然后对文字进行依次编码,存入字典中.
【代码】:
#------------------------------简单难度----------------------------------- def Load_file_easy(path): #[注]返回值是一个set,不可进行数字索引 file = open(path,'r',encoding='utf8') Str = file.read() Str = set(Str) file.close() return Str def Encode_easy(Lstr): Sstr = list(set(Lstr)) Encode_Dict = {} for i in range(len(Lstr)): Encode_Dict[Sstr[i]] = i return Encode_Dict def Decode_easy(Encode_dict): List1 = Encode_dict.keys() List2 = Encode_dict.values() Decode_Dict = dict(list(zip(List2,List1))) return Decode_Dict path = 'SanGuo.txt' Str = list(Load_file_easy(path)) Encode_dict = Encode_easy(Str) Decode_dict = Decode_easy(Encode_dict) #写入同级目录下的文件中,如果不存在文件,则会新创建 #(博主的运行环境是:Ubuntu,win系统的小伙伴可能会在文件末尾加上.txt 啥的,略略略) with open('easy_degree_Encode_dict','w') as file: file.write(str(Encode_dict)) with open('easy_degree_Decode_dict','w') as file: file.write(str(Decode_dict))
【题目要求】:
对《三国演义》的电子文档进行页的划分,以400个字为1页,每页20行20列,那么建立每个字对应的八位密码表示,其中前1~4位为页码,5、6位为行号,7、8位为这一行的第几列。例如:实:,表示字“实”出现在第2413页的12行的09列。 利用此方法对中文文本进行加密和解密。
【分析】
【代码】:
def Load_file_middle(path): with open(path,'r',encoding='utf8') as file: Str = file.read() return Str def Encode(Str): Encode_dict = {} #得到页数 for i in range(len(Str)//400): page = i + 1 temp = Str[(i*400):(400*(i+1))] page_str = str(page) page_str = page_str.zfill(4) #得到行号row和列号col for j in range(400): col = str(j) col = col.zfill(2) #这里稍微说一下:比如02是第三列,12是第13列,112是第13列,看看规律就可以了 if int(col[-2])%2 ==0: col = int(col[-1]) + 1 else: col = int(col[-1]) + 11 row = str(j//20 +1) row = row.zfill(2) col = (str(col)).zfill(2) #print(page_str,row,col) Encode_dict[temp[j]] = page_str+row+str(col) return Encode_dict
def Decode(Encode_dict): List1 = Encode_dict.keys() List2 = Encode_dict.values() Decode_Dict = dict(list(zip(List2,List1))) return Decode_Dict
path = 'SanGuo.txt' Str = list(Load_file_middle(path)) Encode_dict = Encode(Str) Decode_dict = Decode(Encode_dict) with open('middle_low_degree_Encode_dict','w') as file: file.write(str(Encode_dict)) with open('middle_low_degree_Decode_dict','w') as file: file.write(str(Decode_dict))
【题目要求】:现监听到敌方加密后的密文100篇,但是不知道敌方的加密表,但是知道该密码表是由用一个英文字母代替另一个英文字母的方式实现的,现请尝试破译该密码。(注意:只针对英文)
【分析】:
【代码】:
先把爬虫的代码贴出来:
文件名:Crawler.py
import re
import requests
def Crawler(url):
#url2 = 'https://www.diyifanwen.com/yanjianggao/yingyuyanjianggao/'
response = requests.get(url).content.decode('gbk','ignore')
html = response
#正则表达式
#example_for_2 = re.compile(r'<li><a.*?target="_blank".*?href="(.*?)title=(.*?)>.*?</a></li>')
example_for_1 = re.compile(r'<i class="iTit">\s*<a href="(.*?)" target="_blank">.*?</a>')
resultHref =re.findall(example_for_1,html)
resultHref = list(resultHref)
Fil = []
for each_url in resultHref:
each_url = 'https:' + str(each_url)
#构建正则
exam = re.compile(r'<div class="mainText">\s*(.*?)\s*<!--精彩推荐-->')
response2 = requests.get(each_url).content.decode('gbk','ignore')
html2 = response2
result_eassy = re.findall(exam,html2)
Fil.append(result_eassy)
return str(Fil)
def WriteIntoFile(Fil,path):
#写入文件
with open(path,'a') as file:
for i in range(len(Fil)//200):
file.write(Fil[200*i:200*(i+1)])
file.write('\r\n')
if file is not None:
print("success")
def Deleter_Chiness(str):
#删掉汉字、符号等
result1 = re.sub('[<p> </p> u3000]','',str)
result = ''.join(re.findall(r'[A-Za-z]', result1))
return result
主程序:
import Crawler
#产生一个密文加密表
def Creat_cipher_dict(num=5):
cipher_dict = {}
chri = [chr(i) for i in range(97,123)]
for i in range(26-num):
cipher_dict[chri[i]] = chr(ord(chri[i])+num)
for i in range(num):
cipher_dict[chri[26-num+i]] = chr(ord(chri[i]))
return cipher_dict
def Get_Frequency(Str):
Frequency = [0] * 26
cnt = 0
chri = [chr(i) for i in range(97, 123)]
Frequency_dict = {}
for i in range(len(Str)):
Ascii = ord(Str[i]) - 97
# 排除一些还存在的异常字符
if Ascii >= 0 and Ascii <= 25:
Frequency[Ascii] += 1
cnt += 1
Frequency_dict[chr(Ascii+97)] = Frequency[Ascii]
for key in Frequency_dict.keys():
#Frequency[i] = Frequency[i] / cnt
Frequency_dict[key] = Frequency_dict[key]/cnt
Frequency_dict = sorted(Frequency_dict.items(),key = lambda x:x[1],reverse=True)
return dict(Frequency_dict)
def Decode(cipher,org):
Frequency_for_cipher = Get_Frequency(cipher)
Frequency_for_org = Get_Frequency(org)
#print(Frequency_for_org)
#print(Frequency_for_cipher)
Decode_dict = {}
Frequency = list(Frequency_for_org.keys())
i = 0
for key in list(Frequency_for_cipher.keys()):
Decode_dict[key] = Frequency[i]
i +=1
return Decode_dict
def main():
#爬取文章作为提取明文概率的计算文本
for i in range(1,15):
url = 'https://edu.pcbaby.com.cn/resource/yjg/yy/'+'index_'+str(i)+'.html'
try:
Fil = Crawler.Crawler(url)
eassy = Crawler.Deleter_Chiness(Fil)
path = 'eassy_org'
Crawler.WriteIntoFile(path,eassy)
except :
print("爬虫发生意外!")
path = 'eassy_org'
with open(path) as file:
org = str(file.read().splitlines())
org = org.lower()
#创建一个密文
cipher_dict = Creat_cipher_dict(5)
print(cipher_dict)
#这里密文我已经爬取好了,存在本地了,爬取过程同上面大同小异
with open('eassy_cipher','r') as file:
Fil2 = str(file.read().splitlines())
Fil2 = Fil2.lower()
cipher = []
for i in range(len(Fil2)):
if ord(Fil2[i])>=97 and ord(Fil2[i])<=123:
cipher.append(cipher_dict[Fil2[i]])
#至此 ,密文产生好了,每一个字母的概率也计算好了,可以说,工作完成了一大半了
Decode_dict = Decode(cipher,org)
print(Decode_dict)
if __name__ == '__main__':
main()
最后还是将结果贴出来给大家看一下:
上面一个字典是我创建出来的加密表,后一个是根据每个字符出现的概率反解出来的加密表,可见二者的相似程度具有很大的相似度。
完事,收工。溜号!