Python-26_模块-02_python内置模板

---------------------------------- 1、configparser ----------------------------------

"""
[DEFAULT]                       # 无论遍历下面哪个,都会跟着输出default下的键值对
ServerAliveInterval = 45        # default是默认的,下面的字典默认都包含default里的内容
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

"""
#------------------用python生成、配置一个文档-----------------------
import configparser

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'
with open('newmet3', 'w') as configfile:
    config.write(configfile)

######-----------------------增删改查------------------------######
import configparser

config = configparser.ConfigParser()

#---------------------------------------------查
print(config.sections())   #[]

config.read('newmet3')

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.set('yuan','k1','11111')   # 新增块中,增加一个键值对
config.remove_section('topsecret.server.com')       # 删除某个块
config.remove_option('bitbucket.org','user')        # 删除某个块中的键值对

config.write(open('new1', "w"))         # 重新写入文件
configparser

----------------------------------   2、hashlib     ----------------------------------

# 用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
# 1、一个字符串可以转换成一隔密文,不能反解;
# 2、既然不能反解,只能正解,把用户输入的字符串转换成密文形式,与储存的密文相比较,来判断正确与否;
# 3、用MD5生成的密文,任何人都知道,其可以通过撞库反解,有必要对加密算法中添加自定义key再来做加密。
"""
例如:
import hashlib
m = hashlib.md5("newmet".encode("utf8"))  # m=hashlib.sha256()
m.update('hello'.encode('utf8'))
print(m.hexdigest())  # 67ccbb76546cc877a53efa7316434ba3

"""

#-------------------------------- MD5 ----------------------------
# import/# 9bbcaaf06f535aaf08ff5e49f443fe13

# 以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。

#-------------------------------- sha256 ----------------------------

import hashlib

hash = hashlib.sha256('123456'.encode('utf8'))
hash.update('newmet'.encode('utf8'))
print(hash.hexdigest())  # 992549d2f18bca6cfc8b0deef4bb3616128537ba1233e859282de9dfadff252a

# hash = hashlib.sha256()
# hash.update('123456newmet'.encode('utf8'))
# print(hash.hexdigest())  # 992549d2f18bca6cfc8b0deef4bb3616128537ba1233e859282de9dfadff252a


# python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密:
import hmac
h = hmac.new('new'.encode('utf8'))
h.update('met'.encode('utf8'))
print (h.hexdigest())   #96abf343d63dd257a23fef47b103841f
hashlib

----------------------------------   3、json    --------------------------------------

########## 最初版、写入文件、调取文件方式 ###############
# 把字典写入文件a中:
dic='{"name":"newmet"}'
f=open("a","w")
f.write(dic)
# 读取文件a中的文件:
f_read=open("a","r")
data=f_read.read()
data=eval(data)               # eval 方法!!
print(data["name"])
########## 最初版、写入文件、调取文件方式 ###############

import json

# json 可以把python中所以数据类型变成字符串,并且全部单引号('')都转换成双引号("")
dic={"name":"newmet"}
data=json.dumps(dic)
print(data)                     # {"name": "newmet"}
print(type(data))               # <class 'str'>

########## json 写入文件、调取文件方式 ###############
dic={"name":"newmet"}
f=open("b","w")
dic_str=json.dumps(dic)
f.write(dic_str)              # 等价于:json.dump(dic,f)

f_read=open("b","r")
data=json.loads(f_read.read())        # 等价于:data=json.load(f_read)
print(data)                         # {'name': 'newmet'}
print(type(data))                   # <class 'dict'>
########## json 写入文件、调取文件方式 ###############

import pickle
# 和 json 方法一样,写入wb 读取rb(bytes)


# 序列化(pickling):把对象(变量)从内存中变成可存储或传输的过程
# 反序列化(unpickling):把变量内容从序列化的对象重新读到内存里
json

----------------------------------   4、logging    --------------------------------

# import logging

#-------------------- logging.basicConfig ----------------------
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
# 输出结果:
# WARNING:root:warning message
# ERROR:root:error message
# CRITICAL:root:critical message

# 日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
# 默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志

# 1、设置--日志级别,日志格式,输出位置

logging.basicConfig(
    level=logging.DEBUG,        # level= 日志显示级别
    filename="newmet1",        # 文件名称
    filemode="w",               # 读取写入类型
    format="%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s",
    datefmt="%a,%d,%b,%Y,%H:%M:%S"      # 定义日期格式
)

logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

# 结果:
# Tue,27,Nov,2018,16:56:38 Module_logging.py [line:26] DEBUG debug message
# Tue,27,Nov,2018,16:56:38 Module_logging.py [line:27] INFO info message
# Tue,27,Nov,2018,16:56:38 Module_logging.py [line:28] WARNING warning message
# Tue,27,Nov,2018,16:56:38 Module_logging.py [line:29] ERROR error message
# Tue,27,Nov,2018,16:56:38 Module_logging.py [line:30] CRITICAL critical message

# 可见在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open('test.log','w')),
        默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息


#-------------------- logging.getLogger([name]) ----------------------

# 2、logger对象

logging.debug()、
logging.info()、
logging.warning()、
logging.error()、
logging.critical()
# 分别用以记录不同级别的日志信息
# logging.basicConfig()(用默认日志格式(Formatter)为日志系统建立一个默认的流处理器(StreamHandler),
# 设置基础配置(如日志级别等)并加到root logger(根Logger)中)这几个logging模块级别的函数

# 另外还有一个模块级别的函数是logging.getLogger([name])(返回一个logger对象,如果没有指定名字将返回root logger)
# 在新增的日志文件和输出窗口,两个位置均输出内容!!

logger = logging.getLogger()
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('newmet2.log')

# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()

fm = logging.Formatter('%(asctime)s %(message)s')

fh.setFormatter(fm)
ch.setFormatter(fm)

logger.addHandler(fh) #logger对象可以添加多个fh和ch对象
logger.addHandler(ch)

logger.setLevel("DEBUG")

logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')

#---------------------------------------------------------------------



"""
# 日志操作py文件,需要调用的时候,直接连接这个接口就好:
def logger():
    logger = logging.getLogger()
    # 创建一个handler,用于写入日志文件
    fh = logging.FileHandler('newmet2.log')

    # 再创建一个handler,用于输出到控制台
    ch = logging.StreamHandler()

    fm = logging.Formatter('%(asctime)s %(message)s')

    fh.setFormatter(fm)
    ch.setFormatter(fm)

    logger.addHandler(fh)
    logger.addHandler(ch)
    logger.setLevel("DEBUG")

    return logger
logger=logger()         # 直接调用日志文件接口

logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')

"""


########   实例   #######
import os
import time
import logging
from config import settings


def get_logger(card_num, struct_time):

    if struct_time.tm_mday < 23:
        file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon, 22)
    else:
        file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon+1, 22)

    file_handler = logging.FileHandler(
        os.path.join(settings.USER_DIR_FOLDER, card_num, 'record', file_name),
        encoding='utf-8'
    )
    fmt = logging.Formatter(fmt="%(asctime)s :  %(message)s")
    file_handler.setFormatter(fmt)

    logger1 = logging.Logger('user_logger', level=logging.INFO)
    logger1.addHandler(file_handler)
    return logger1
logging

----------------------------------   5、os    --------------------------------------

import os

v=os.getcwd()                 # 获取当前工作目录,即当前python脚本工作的目录路径
                              # E:Python+AI
ewmet7_模块2_python标准库
# os.chdir("test1")           # 改变当前脚本工作目录;
# print(os.getcwd())          # E:Python+AI
ewmet7_模块2_python标准库	est1

os.curdir                            # 返回当前目录: ('.')
os.pardir                            # 获取当前目录的父目录字符串名:('..')
os.makedirs('test1/test2')         # 可生成多层递归目录
os.removedirs('test1')              # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('test1')                   # 生成单级目录;相当于shell中mkdir dirname
os.rmdir('test1')                   # 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('test1')                 # 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove('test1')                  # 删除一个文件
os.rename("oldname","newname")    # 重命名文件/目录
os.stat('Module_time')             # 获取文件/目录信息
os.sep                              # 输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
os.linesep                          # 输出当前平台使用的行终止符,win下为"
",Linux下为"
"
os.pathsep                          # 输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name                             # 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")          # 运行shell命令,直接显示
os.environ                          # 获取系统环境变量
os.path.abspath("path")             # 返回path规范化的绝对路径
os.path.split("path")               # 将path分割成目录和文件名二元组返回
os.path.dirname("path")             # 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename("path")            # 返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists("path")              # 如果path存在,返回True;如果path不存在,返回False
os.path.isabs("path")               # 如果path是绝对路径,返回True
os.path.isfile("path")              # 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir("path")               # 如果path是一个存在的目录,则返回True。否则返回False

v=os.path.join("path1", "path2")  # 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略!!!

os.path.getatime("path")           # 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime("path")           # 返回path所指向的文件或者目录的最后修改时间

print(v)
os

----------------------------------   6、random    -------------------------------

import random

res=random.random()                 # (0.1)------之间的浮点数float
res=random.randint(1,3)             # [1,3]------之间的整数
res=random.randrange(1,3)           # [1,3)------之间的整数,不包括3
res=random.choice([1,21,3,4,5])     # 随机选择可迭代对象的一个元素
res=random.sample([1,21,3,4,5],2)   # [1, 4]  随机选择可迭代对象的2个元素
res=random.uniform(1,5)             # (1,5------之间任意的浮点数     1.3720242515710894


res=[1,2,3,4,5]
random.shuffle(res)                 # 随机打乱列表中的元素位置

# print(res)


# 定义一个6位数随机验证码:
def v_code():
    res=""
    for i in range(6):                             # 执行6次循环
        num=random.randint(0,9)                     # 随机数字 0--9
        capital=chr(random.randint(65,90))          # 随机大写字母 A--Z
        lowercase=chr(random.randint(97,122))       # 随机小写字母 a--z
        alp = random.choice([capital, lowercase])   # 随机一个大写或小写字母 a--Z
        v=str(random.choice([num,alp]))             # 随机字母或数字
        res+=v
    return res
print(v_code())
random

----------------------------------   7、re    --------------------------------------

# 正则表达式(或 RE)是一种小型的、高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现。
# 正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

"""
name="fse11hnoi33oiio55nboi5non65non2nnono23"       # 输出其中的数字
import re
v=re.findall("d+",name)
print(v)                     # ['11', '33', '55', '5', '65', '2', '23']

"""
###################   正则表达式   ######################
import re

# 1、普通字符:大多数字符和字母都会和自身匹配
# print(re.findall("new","nfewnewfefefoijgnew"))      # ['new', 'new']

# 2、元字符:.^ $ *+ ? {}[] | ( ) 

######################  一、元字符  . ^ $ * + ? {}  ######################
######################  元字符里面没有特殊符号  ######################
# 1) .
# .可以代表任意一个字符(一个点 . 只代表一个字符)
v=re.findall("n..w","nfewnewfefefoijndsffwgnew")
print(v)                # ['nfew']

# 2)^
# 匹配以某个字符开头的,开头是该字符,匹配成功、继续匹配;否者直接输出空
v=re.findall("^n..w","nfewnewfefefoijndsffwgnew")
print(v)                # ['nfew']

# 3)$
# 匹配以某个字符结尾的,结尾是该字符,匹配成功、继续匹配;否者直接输出空
v=re.findall("n..w$","nfewnewfefefoijndsffwgnew")
print(v)                # []

# 4)遇到处理重复的字符时,利用 *+ ? {} 这4个表示重复
#      *    匹配  [0,+∞]              # 贪婪匹配--->转换成非贪婪匹配  在 *、+ 后面加上?按最小匹配
#      +    匹配  [1,+∞]              # 贪婪匹配
#     ?    匹配  [0,1]  0次或1次
#     {}    可以表示 * + ? 这三种所有的情况:{0,+∞} {1,+∞} {0,1}
#           {5}--代表可以重复5次,{5,10}--代表可以重复5--10次之间任意次数
v=re.findall("newf*","newfffmet")
print(v)            # ['newfff']
v=re.findall("newf+","newfffmet")
print(v)            # ['newfff']
v=re.findall("newf?","newfffmet")
print(v)            # ['newf']
v=re.findall("newf{2}","newfffmet")
print(v)            # ['newff']

######################  二、元字符  [ ] | ( )   ######################
######################  元字符里面没有特殊符号  ######################
# 1) [ ]  里面可以有3个特殊字符:- ^    --------区间   匹配到就失败   转义符
# [ ]
v=re.findall("x[yz]","xyddxziixi")      # 匹配 xy 或 xz
print(v)               # ['xy', 'xz']
# [ a - z ]            # (a-z)之间的任意一个字母
v=re.findall("x[a-z]","xyddxziixi")      # 匹配 x+(a-z)之间的任意一个字母
print(v)               # ['xy', 'xz', 'xi']

# 转义符-----  

# 反斜杠后边跟元字符去除特殊功能,比如.
# 反斜杠后边跟普通字符实现特殊功能,比如d
#     d  匹配任何十进制数;它相当于类 [0-9]。
#     D 匹配任何非数字字符;它相当于类 [^0-9]。
#     s  匹配任何空白字符;它相当于类 [ 	

fv]。
#     S 匹配任何非空白字符;它相当于类 [^ 	

fv]。
#     w 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。
#     W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]
#       匹配一个特殊字符边界,比如空格 ,&,#等
v=re.findall(r"I","I am LIST")      # 匹配 "I am LIST"中,I是单独单词的部分
print(v)               # ['I']

v=re.findall('c\\l','abcle')
print(v)        #['c\l']
v=re.findall(r'c\l','abcle')
print(v)        #['c\l']
v = re.findall('blow', 'blow')
print(v)        # []
v = re.findall(r'blow', 'blow')
print(v)        # ['blow']

# 2) ( )     组
m = re.findall(r'(ad)+', 'add')
print(m)

v = re.search('(?P<id>d{2})/(?P<name>w{3})', '23/com')    # search 只查找输出第一个符合要求的对象
print(v.group())   # 23/com                          # ?P<id>   ?P<name>   给要查找的数据定义一个分组,
print(v.group('id'))  # 23                          # search 输出的是个分组信息,group调出具体的数据

# 3) |  或
v=re.search('(ab)|d','rabhdg8sd')
print(v.group())                        # ab
v=re.findall(r'(ab)|d','rabhdg8sd')
print(v)                        # ab


###########  re 方法  ###########

# re.findall("e","newmet")        # 返回所有满足匹配条件的结果,放在列表里
# re.search("e","newmet").group() # 函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以
#                                  # 通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None
# re.match("e","newmet").group()  # 同search,不过尽在字符串开始处进行匹配
v=re.split("[nw]","newmet")     # 先按'n'分割得到''和'ewmet',在对''和'ewmet'分别按'w'分割
print(v)                          # ['', 'e', 'met']

ret=re.sub('d','abc','new2met3',1)    # 替换
print(ret)                               # newabcmet3
ret=re.subn('d','abc','new2met3')
print(ret)                              # ('newabcmetabc', 2)

v=re.compile('d{3}')                   # 编译规则
ret=v.search('abc123eeee')             # 输入对象字符串
print(ret.group())                      # 123

v=re.finditer('d','new2134met')      # 把复核条件的对象,放入迭代器,需要的时候一个个调出来
print(v)                                # <callable_iterator object at 0x0000000000656400>
print(next(v).group())      # 2
print(next(v).group())      # 1
print(next(v).group())      # 3
print(next(v).group())      # 4

# 补充一:
ret = re.findall('www.(new|newmet).top', 'www.newmet.top')
print(ret)  # ['newmet']     这是因为findall会优先把匹配结果组里内容返回,如果想要匹配结果,取消权限即可

ret = re.findall('www.(?:new|newmet).top', 'www.newmet.top')
print(ret)  # ['www.newmet.top']

# 补充二:
print(re.findall("<(?P<tag_name>w+)>w+</(?P=tag_name)>","<h1>hello</h1>"))
print(re.search("<(?P<tag_name>w+)>w+</(?P=tag_name)>","<h1>hello</h1>"))
print(re.search(r"<(w+)>w+</1>","<h1>hello</h1>"))

# 补充三:
#匹配出所有的整数
#ret=re.findall(r"d+{0}]","1-2*(60+(-40.35/5)-(-4*3))")
ret=re.findall(r"-?d+.d*|(-?d+)","1-2*(60+(-40.35/5)-(-4*3))")
ret.remove("")
print(ret)              # ['1', '-2', '60', '5', '-4', '3']
re

----------------------------------   8、shelve    -------------------------------

# shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,
# 可读可写;key必须为字符串,而值可以是python所支持的数据类型

import shelve

f = shelve.open(r'shelve.txt')

f['stu1_info']={'name':'alex','age':'18'}
f['stu2_info']={'name':'alvin','age':'20'}
f['school_info']={'website':'oldboyedu.com','city':'beijing'}


f.close()

print(f.get('stu_info')['age'])
shelve

----------------------------------   9、sys    ----------------------------------

import sys

print(sys.argv)         # ['E:/Python+AI/newmet/07_模块/02_python标准库/Module_sys.py']
                        # 命令行参数List,第一个元素是程序本身路径

# sys.exit(1)           # 退出程序,正常退出时exit(0)

print(sys.version)      # 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)]
                        # 获取Python解释程序的版本信息
print(sys.path)         # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
print(sys.platform)     # 返回操作系统平台名称



#进度条:
import time
for i in range(100):
    sys.stdout.write("#")
    time.sleep(0.1)
    sys.stdout.flush()
sys

----------------------------------   10、time    -------------------------------

import time

# 1、时间戳 Timestamp
print(time.time())          # 结果:1542785865.6010022秒  这个世界是从1970年1月1号零点开始算起,到现在。

# 2、localtime -- 结构化时间--当地时间 struct_time
print(time.localtime())     # time.struct_time+(年,月,日,时,分,秒,一周中第几天,一年中第几天,夏令时)
# time.struct_time(tm_year=2018, tm_mon=11, tm_mday=21, tm_hour=15, tm_min=44, tm_sec=43, tm_wday=2, tm_yday=325, tm_isdst=0)
t=time.localtime()
print(t.tm_year)            # 2018    获取年月日,时间,星期几

# 3、gmtime -- 世界标准时间--和localtime类似
print(time.gmtime())

# 4、时间戳、结构化时间--相互转换:
print(time.localtime(154278512))
print(time.mktime(time.localtime()))

# 5、结构化时间、格式化字符串时间--相互转换  (Format string  格式化字符串时间)
print(time.strftime("%Y-%m-%d %X", time.localtime()))   # 结果:2018-11-21 16:25:18
print(time.strptime('2018-10-05 16:37:06', '%Y-%m-%d %X'))  # 一一对应

# 6、asctime -- 如果没有参数,将会将time.localtime()作为参数传入
print(time.asctime())           #结果:Wed Nov 21 16:32:01 2018

# 7、ctime -- 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。
print(time.ctime())             #结果:Wed Nov 21 16:32:01 2018

# 8、sleep
print(time.sleep(2))

# 9、clock
# 这个需要注意,在不同的系统上含义不同。在UNIX系统上,它返回的是“进程时间”,它是用秒表示的浮点数(时间戳)。
# 而在WINDOWS中,第一次调用,返回的是进程运行的实际时间。而第二次之后的调用是自第一次调用以后到现在的运行
# 时间,即两次时间差。

# 10、另外一种时间模块:
import datetime
print(datetime.datetime.now())          # 结果:2018-11-21 16:45:09.646002
time

----------------------------------   11、XML    -------------------------------

# xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,
# 古时候,在json还没诞生的黑暗年代,大家只能选择用xml,至今很多传统公司如金融行业的很多
# 系统的接口还主要是xml。

# xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:
import xml.etree.ElementTree as ET

tree = ET.parse("xml_ss")          # parse 解析     xml_ss(对象)--->赋值给tree
root = tree.getroot()
print(root.tag)                     # 结果:data(最外围标签---简称为第0环,内部按第1环、第2环...依次称)

# 遍历xml文档、tag(标签)、attrib(属性)、text(文本)
for child in root:
    print(child.tag, child.attrib)  # child.tag 第1环标签   child.attrib 属性
    for i in child:
        print(i.tag, i.text)        # i.tag 第2环标签     i.text 取出每个标签对应得--文本

# 只遍历year 节点
for node in root.iter('year'):
    print(node.tag, node.text)
# ---------------------------------------

import xml.etree.ElementTree as ET

tree = ET.parse("xml_ss")
root = tree.getroot()

# 修改 root.iter
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("updated", "yes")
tree.write("xml_ss1")           # 对上述修改进行更新或者复制到另外一个新的文本中

# 删除node    findall、find
for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)
tree.write('xml_ss2')


##############  自己创建xml文档: #################
import xml.etree.ElementTree as ET

new_xml = ET.Element("namelist")            # 主标签 namelist

name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
age = ET.SubElement(name, "age", attrib={"checked": "no"})
sex = ET.SubElement(name, "sex")
sex.text = '33'

name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'

et = ET.ElementTree(new_xml)  # 生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)

# ET.dump(new_xml)  # 打印生成的格式
XML

简易计算器:

 1 def muldiv_calc(form, sym):  # 乘除计算,form列表、sym--*或者/
 2     a = form.index(sym)  # 当前字符sym所在列表form中的索引位置
 3     if sym == "*" and form[a + 1] != "-":
 4         f = float(form[a - 1]) * float(form[a + 1])
 5     elif sym == "/" and form[a + 1] != "-":
 6         f = float(form[a - 1]) / float(form[a + 1])
 7     elif sym == "*" and form[a + 1] == "-":
 8         f = -float(form[a - 1]) * float(form[a + 2])
 9     elif sym == "/" and form[a + 1] == "-":
10         f = -float(form[a - 1]) / float(form[a + 2])
11     if form[a + 1] != "-":
12         del form[a - 1], form[a - 1], form[a - 1]  # 删除运算的这3个元素
13         form.insert(a - 1, str(f))  # 将求的结果f插入到删除的第一个元素位置
14     else:
15         del form[a - 1], form[a - 1], form[a - 1], form[a - 1]
16         form.insert(a - 1, str(f))
17     return form
18 
19 
20 def calc(form):  # 主计算程序
21     form = re.findall("([d.]+|+|-|*|/)", form)
22     num = 0
23     while form:
24         if "*" in form and "/" not in form:  # 先计算乘除
25             muldiv_calc(form, "*")
26         elif "*" not in form and "/" in form:
27             muldiv_calc(form, "/")
28         elif "*" in form and "/" in form:
29             a = form.index("*")
30             b = form.index("/")
31             if a < b:
32                 muldiv_calc(form, "*")
33             else:
34                 muldiv_calc(form, "/")
35         else:  # 乘除已经计算完,下面计算加减
36             if form[0] == "-":  # 如果列表第一个元素是“-” 将第1、2元素合并
37                 form[0] = form[0] + form[1]  # 删除第2个元素
38                 del form[1]
39             num += float(form[0])
40             for i in range(1, len(form), 2):
41                 if form[i] == "+"and form[i + 1] == "-":
42                     num -= float(form[i + 2])
43                 elif form[i] == "-"and form[i + 1] == "-":
44                     num += float(form[i + 2])
45                 elif form[i] == "+" and form[i + 1] != "-":
46                     num += float(form[i + 1])
47                 elif form[i] == "-"and form[i + 1] != "-":
48                     num -= float(form[i + 1])
49 
50             break
51     return num
52 
53 
54 def calculate(form):
55     ex = []  # 存储'('出现的位置
56     ans = 0  # 保存结果
57     if '(' not in form:  # 如果括号都处理完成了,直接调用calc函数返回结果
58         ans = calc(form)
59         return ans
60     for i in range(len(form)):
61         if form[i] == '(':
62             ex.append(i)  # ex=[6,7]                          # 纪录 '(' 出现的位置
63         elif form[i] == ')':                                 # 遇到 ')'后。就可以计算第一个括号里的值
64             temp = 0                                          # 定义一个变量 存储括号表达式的结果
65             sub = form[ex[len(ex) - 1] + 1:i]                 # 获取括号里的表达式
66             temp = calc(sub)                                  # 调用calc函数计算括号里的表达式的值
67             form = form[0:ex[len(ex) - 1]] + str(temp) + form[i + 1:len(form) + 1]  # 去掉刚才的括号表达式,并用temp代替,返回一个新的表达式
68             ex.pop()                                          # 删除刚才计算完的括号表达式里面 '(' 的位置
69             return calculate(form)                            # 递归计算新的表达式,直道所有的括号处理完毕
70 
71 
72 formula ="21 - 34 * ( 14 / 2 - 5 * ( 6 - 4 ) ) + 100 / ( 25 - 2 * 5 )"
73 formula1 = "21 - ( -4 )"
74 print(eval(formula))
75 print(eval(formula1))
76 v = calculate(formula)
77 v1 = calculate(formula1)
78 print(v)
79 print(v1)
简易计算器
原文地址:https://www.cnblogs.com/newmet/p/10037982.html