作业一:实现一个同时支持中文和英文的对称加解密类

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())))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值