class MyEnDecryption():
__g_hans_list = None
""" 缓存get_hans_list的结果,不用每次实例化都调用get_hans_list """
def __new__(cls, *args, **kwargs):
if cls.__g_hans_list is None:
cls.__g_hans_list = cls.get_hans_list(kwargs.get("url"))
return super(MyEnDecryption, cls).__new__(cls)
def __init__(self, url=""):
# self.input_msg = input_msg
self.result = None
self.url = url
self.__hans_list = self.__g_hans_list if self.__g_hans_list else self.get_hans_list(
url)
self.__hans_dict = self.list_to_dict(self.__hans_list)
self.__encryt_result = None
self.__decryt_result = None
@staticmethod
def get_hans_list(url):
# print("get_hans_list")
html = requests.get(url)
# html = get(url)
pattern = "href='/hans/(.*)' "
# 获取到2500个汉字
hans_list = re.findall(pattern, html.text)
return hans_list
@staticmethod
def list_to_dict(input_list):
assert (isinstance(input_list, list))
d = {}
for i, el in enumerate(input_list):
d.update({el: i+1})
# if isinstance(input_list, list): raise Exception
return d
def do_encrypt(self, input_msg):
result = ""
for i_char in input_msg:
# result += self.__hans_dict.get(i_char, "") + "|"
value = ord(i_char)
if any([64 < value < 78, 96 < value < 110]):
result_char = chr(value+13) + "|"
result += result_char
elif any([77 < value < 91, 109 < value < 123]):
result_char = chr(value-13) + "|"
result += result_char
else:
# 汉字加密
for i, el in enumerate(self.__hans_list):
if i_char == el:
result += str(i) + "|"
self.__encryt_result = result
return self.__encryt_result
def do_decrypt(self, encry_str):
result = ""
str_list = encry_str.split("|")
try:
str_list.remove("")
except ValueError:
pass
for i in str_list:
# if len(i) > 1:
# for j in i:
try:
value = ord(i)
if any([64 < value < 78, 96 < value < 110]):
result_char = chr(value+13)
result += result_char
elif any([77 < value < 91, 109 < value < 123]):
result_char = chr(value-13)
result += result_char
except:
#汉字解密
result += self.__hans_list[int(i)]
self.__decryt_result = result
return self.__decryt_result
def get_encryt_result(self):
return self.__encryt_result
def get_decryt_result(self):
return self.__decryt_result
def get_hans_dict(self):
return self.__hans_dict
if __name__ == "__main__":
input_msg = input("请输入加密内容:\n")
url = "https://www.zdic.net/zd/zb/cc1/"
ed = MyEnDecryption(url=url)
#多次实例化,hans_list使用缓存数据
ed2 = MyEnDecryption(url=url)
#加密
print("加密后的结果:{}".format(ed.do_encrypt(input_msg)))
#解密
print("解密后的结果:{}".format(ed.do_decrypt(ed.get_encryt_result())))