首页 > 编程语言 > 详细

Python之旅的第18天(configparser、hashlib模块)

时间:2020-03-11 23:58:32      阅读:120      评论:0      收藏:0      [点我收藏+]

今天讲的两个模块都没啥意思,可能是因为目前接触的不多,感觉用处不是很大,今天主要是用re正则表达式做一个计算器,模拟了一下eval到底是怎么操作的

一、configparser模块  

import configparser
# 来看一个好多软件的常见文档格式如下:
# [DEFAULT]
# ServerAliveInterval = 45
# Compression = yes
# CompressionLevel = 9
# ForwardX11 = yes
#
# [bitbucket.org]
# User = hg
#
# [topsecret.server.com]
# Port = 50022
# ForwardX11 = no

# 引入configpraser模块实现以上文件编辑
# config = configparser.ConfigParser()
# config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,
#                      ‘Compression‘: ‘yes‘,
#                      ‘CompressionLevel‘: ‘9‘}
#
# config[‘bitbucket.org‘] = {}
# config[‘bitbucket.org‘][‘User‘] = ‘hg‘
# config[‘topsecret.server.com‘] = {}
# topsecret = config[‘topsecret.server.com‘]
# topsecret[‘Host Port‘] = ‘50022‘  # mutates the parser
# topsecret[‘ForwardX11‘] = ‘no‘  # same here
# config[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘ < br >
# with open(‘example.ini‘, ‘w‘) as configfile:
#     config.write(configfile)

# 关于configpraser的增删改查
import configparser

# config = configparser.ConfigParser()
# 
#
# print(config.sections())   #[]
# 
# config.read(‘example.ini‘)
# 
# print(config.sections())   #[‘bitbucket.org‘, ‘topsecret.server.com‘]
# 
# print(‘bytebong.com‘ in config)# False
# 
# print(config[‘bitbucket.org‘][‘User‘]) # hg
# 
# print(config[‘DEFAULT‘][‘Compression‘]) #yes
# 
# print(config[‘topsecret.server.com‘][‘ForwardX11‘])  #no
# 
# 
# for key in config[‘bitbucket.org‘]:
#     print(key)
# 
# 
# # user
# # serveraliveinterval
# # compression
# # compressionlevel
# # forwardx11
# 
# 
# print(config.options(‘bitbucket.org‘))#[‘user‘, ‘serveraliveinterval‘, ‘compression‘, ‘compressionlevel‘, ‘forwardx11‘]
# print(config.items(‘bitbucket.org‘))  #[(‘serveraliveinterval‘, ‘45‘), (‘compression‘, ‘yes‘), (‘compressionlevel‘, ‘9‘), (‘forwardx11‘, ‘yes‘), (‘user‘, ‘hg‘)]
# 
# print(config.get(‘bitbucket.org‘,‘compression‘))#yes
# 
# 
# 删,改,增(config.write(open(‘i.cfg‘, "w")))
# 
# 
# config.add_section(‘yuan‘)
# 
# config.remove_section(‘topsecret.server.com‘)
# config.remove_option(‘bitbucket.org‘,‘user‘)
# 
# config.set(‘bitbucket.org‘,‘k1‘,‘11111‘)
# 
# config.write(open(‘i.cfg‘, "w"))
# 

二、hashlib模块

import hashlib
# 用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
# import hashlib
#
# m = hashlib.md5()  # m=hashlib.sha256()
#
# m.update(‘hello‘.encode(‘utf8‘))
# print(m.hexdigest())  # 5d41402abc4b2a76b9719d911017c592
#
# m.update(‘alvin‘.encode(‘utf8‘))
#
# print(m.hexdigest())  # 92a7e713c30abbb0319fa07da2a5c4af
#
# m2 = hashlib.md5()
# m2.update(‘helloalvin‘.encode(‘utf8‘))
# print(m2.hexdigest())  # 92a7e713c30abbb0319fa07da2a5c4af
# 以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
# import hashlib
#
# # ######## 256 ########
#
# hash = hashlib.sha256(‘898oaFs09f‘.encode(‘utf8‘))
# hash.update(‘alvin‘.encode(‘utf8‘))
# print(hash.hexdigest())  # e79e68f070cdedcfe63eaf1a2e92c83b4cfb1b5c6bc452d214c1b7e77cdfd1c7
# python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密:
# import hmac
# h = hmac.new(‘alvin‘.encode(‘utf8‘))
# h.update(‘hello‘.encode(‘utf8‘))
# print (h.hexdigest())#320df9832eab4c038b6c1d7ed73a5940

三、re正则的计算器(还不是很完善,和我算的结果一样,就是不知道为啥和eval的不一样)

import re
def hefa(test):
    l_kuohao = re.findall(\(,test)
    # print(len(l_kuohao))
    r_kuohao = re.findall(\),test)
    # print(len(r_kuohao))
    zimu = re.findall([a-z\|A-Z]+,test)
    # print(len(zimu))
    xiaoshudian = re.findall(r\.\.,test)
    # print(len(xiaoshudian))
    if len(l_kuohao) ==len(r_kuohao) and len(zimu) == 0 and len(xiaoshudian) == 0:
        return True
    else:
        return False

def input_1():
    while True:
        test = input(请输入计算内容>>>)
        if hefa(test) == True:
            break
        else:
            print(请重新输入)
    return test

def cheng(test):
    test = test.replace(--,+)
    test = test.replace(+-,-)
    test = test.replace( , ‘‘)
    while True:
        if len(re.findall([*/],test)) != 0 :
            test_chchu = re.search(-?\d+\.?\d*[*/]-?\d+\.?\d*,test).group()
            if len(re.split(\*,test_chchu)) == 2:
                test_ji =float(re.split(\*,test_chchu)[0].strip()) * float(re.split(\*,test_chchu)[1].strip())
                test = test.replace(test_chchu,str(test_ji))
            else:
                test_chu = float(re.split(\/,test_chchu)[0].strip()) / float(re.split(\/,test_chchu)[1].strip())
                test = re.sub(test_chchu,str(test_chu),test)
        else:
            break
    return test

def add_(test):
    test = test.replace(--,+)
    test = test.replace(+-,-)
    test = test.replace( ,‘‘)
    test_list = re.findall(-?\d+\.?\d*,test)
    a = 0
    for i in test_list:
        a += float(i)
    test = str(a)

    # while True:
    #     # print(len(re.findall(‘-?\d+\.?\d*[+\-]-?\d+\.?\d*‘,test)))
    #     if len(re.findall(‘-?\d+\.?\d*[+\-]-?\d+\.?\d*‘,test)) != 0 :
    #         test_jiajian = re.search(‘-?\d+\.?\d*[+\-]-?\d+\.?\d*‘,test).group()
    #         if len(re.split(‘\+‘,test_jiajian)) == 2:
    #             test_he =float(re.split(‘\+‘,test_jiajian)[0].strip()) + float(re.split(‘\+‘,test_jiajian)[1].strip())
    #             test = test.replace(test_jiajian,str(test_he))
    #         else:
    #             test_cha = float(re.split(r‘-‘,test_jiajian)[0].strip()) - float(re.split(r‘-‘,test_jiajian)[1].strip())
    #             test = re.sub(test_jiajian,str(test_cha),test)
    #     else:
    #         break
    return test


def kuohao(test):
    # print(type(test),test)
    test_old = re.search(\([^()]*\),test).group()
    # print(type(test_old),test_old)
    test_old_lone = test_old.replace((, ‘‘)
    # print(test_old_lone)
    test_old_lone = test_old_lone.replace(), ‘‘)
    # print(test_old_lone)
    a = cheng(test_old_lone)
    # print(a)
    test_new = add_(a)
    # print(type(test_new),test_new)
    test = test.replace(test_old, test_new)
    # print(test)
    return test


if __name__ == __main__:
    # test = input_1()
    test = 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
    test = test.replace( ,‘‘)
    print(test)
    while True:
        if len(re.findall(\(,test)) != 0 :
            test = kuohao(test)
            print(test)
        else:
            break
    a = cheng(test)
    # print(type(a),a)
    test_new = add_(a)
    print(type(test_new),test_new)
    print(eval(1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )))
    if test_new == eval(test):
        print(test_new)

今天结束的好早,好开心,要睡觉了

 

来看一个好多软件的常见文档格式如下:

Python之旅的第18天(configparser、hashlib模块)

原文:https://www.cnblogs.com/xiaoyaotx/p/12466392.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!