python学习八(基础知识)
python基础学习八
本章内容
- time模块
- random模块
- os模块
- sys模块
- hashlib模块
- logging模块
- configparser模块
- re模块
1.time模块
time( )函数用于返回当前时间的时间戳(从1970年1月1日00时00分00秒到现在的浮点秒数)
import time
print(time.time())
#结果
1564457397.7353609
localtime( )函数的作用是格式化时间戳为本地时间(struct_time类型)。如果secs参数未传入,就以当前时间为转换标准import time
import time
print(time.localtime())
#结果
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=30, tm_hour=11, tm_min=31, tm_sec=2, tm_wday=1, tm_yday=211, tm_isdst=0)
strftime()只能接受struct_time类型的参数,若提供的是9位元素的时间元组,则需要将其转化为时间戳再转化为struct_time类型的时间元组
import time
lt = time.localtime()
print(time.strftime('%Y-%m-%d %H:%M:%S',lt))
#结果
2019-07-30 11:33:23
sleep()函数推迟调用线程的运行,可通过参数secs指秒数,表示进程挂起的时间
import time start = time.time() print(1) time.sleep(2) end = time.time() print(end-start)
2.random模块
- random.random()随机生成一个大于0小于1的随机数
- random.uniform(a,b)用于生成一个指定范围内的随机浮点数,两个参数其中一个是下限一个是上限。(a<b)
- random.randint(a, b) 用于生成一个指定范围内的整数,(a<=N<=b)
- random.randrange([start], stop[, step])从指定范围内,按指定的基数递增的集合中获取一个随机数
- random.choice(sequence)参数sequence表示一个有序类型,从序列中获取一个随机元素
- random.shuffle(x[, random])用于将一个列表中的元素打乱,即将列表内的元素随机排列
- random.sample(sequence, k)从指定的序列中随机获取指定长度的片断并随机排列,sample函数不会修改原有序列
import random print(random.random()) #0.8397446571599448 print(random.uniform(1,7)) #1.1422337492701922 print(random.randint(1,10)) #8 print(random.randrange(10,20,2)) #16 print(random.choice([1,3,5,7,9])) #5 li = [1,3,5,7,9] random.shuffle(li) print(li) #[3, 9, 5, 1, 7] lis = [1,2,3,4] tup = (5,6,7,8) str = "Helloworld!" samp_lis = random.sample(lis,3) samp_tup = random.sample(tup,3) samp_str = random.sample(str,3) print(samp_lis) #[4, 2, 1] print(samp_tup) #[7, 6, 5] print(samp_str) #['!', 'e', 'r']
3.os模块
os 模块提供了非常丰富的方法用来处理文件和目录。
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd
os.curdir 返回当前目录: ('.')
os.pardir 获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2') 可生成多层递归目录
os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename("oldname","newname") 重命名文件/目录
os.stat('path/filename') 获取文件/目录信息
os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep 输出用于分割文件路径的字符串
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
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
4.sys模块
sys.argv 命令行参数List,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(0)
sys.version 获取Python解释程序的版本信息
sys.maxint 最大的Int值
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.path.append ("自定义模块路径")
sys.platform 返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]
5.hashlib模块
用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
import hashlib
m = hashlib.md5()
print(m)
m.update("hello world".encode('utf8'))
print(m.hexdigest())
m1 = hashlib.sha256()
print(m1)
m1.update("hello world".encode('utf8'))
print(m1.hexdigest())
6.logging模块
python的logging模块提供了标准的日志接口,logging的日志可以分为 debug(), info(), warning(), error() and critical() 5个级别
1.简单配置方式 logging.basicConfig()函数
import logging
logging.basicConfig(filename='log.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10,
filemode='a') #2019-07-06 18:59:04 PM - root - CRITICAL -day18-04: critical message
logging.debug("debug message1")
logging.info("info message1")
logging.warning("warning message1")
logging.error("error message1")
logging.critical("critical message1")
2.日志流处理流程
#1.创建logger,如果参数为空则返回root logger logger = logging.getLogger("atm") logger.setLevel(logging.DEBUG) #2.创建handler fh = logging.FileHandler("..\logs\\atm.log",encoding="utf-8") ch = logging.StreamHandler() #3.设置输出日志格式 formatter = logging.Formatter( fmt="%(asctime)s %(filename)s %(message)s", datefmt="%Y/%m/%d %X" ) #4.为handler指定输出格式,注意大小写 fh.setFormatter(formatter) ch.setFormatter(formatter) logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')
7.configparser模块
用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。
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('example.ini', 'w') as configfile:
config.write(configfile)
config.read('example.ini')
print(config.sections())
print(config.defaults())
print(config['bitbucket.org']['user'])
for key in config['topsecret.server.com']:
print(key)
print(config.has_section('topsecret.server.com'))
config.remove_option('bitbucket.org','user')
config.write(open('example.ini','w'))

8.re模块
'.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)
'$' 匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以
'*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a']
'+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']
'?' 匹配前一个字符1次或0次
'{m}' 匹配前一个字符m次
'{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']
'|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'
'(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c
'\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的
'\Z' 匹配字符结尾,同$
'\d' 匹配数字0-9
'\D' 匹配非数字
'\w' 匹配[A-Za-z0-9]
'\W' 匹配非[A-Za-z0-9]
's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t'
\b 匹配一个特殊边界,也就是指单词和空格间的位置
'(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}
import re
#re.findall 把所有匹配到的字符放到以列表中的元素返回
ret = re.findall('w\w{2}l','hello world')
print(ret)
ret1 = re.findall('alex','alexxdsfagasgagae alexoioppppp')
print(ret1)
#'.'默认匹配除\n之外的任意一个字符
ret2 = re.findall('w..l','hello world')
print(ret2)
#'^' 匹配字符开头
ret3 = re.findall('^h...o','hello world')
print(ret3)
#'$'匹配字符结尾
ret4 = re.findall('...d$','hello world')
print(ret4)
#'*'匹配*号前的字符0次或多次,重复匹配
ret5 = re.findall('hel*','hellllllo world helloworld,world ello')
print(ret5)
#'+' 匹配前一个字符1次或多次
ret6 = re.findall('hel+o','hellllllo world helloworld,world ello')
print(ret6)
#'?'匹配前一个字符1次或0次
ret7 = re.findall('hel?','hellllllo world helloworld,world ello')
print(ret7)
#'{m}'匹配前一个字符m次
ret8 = re.findall('hel{6}o','hellllllo world helloworld,world ello')
print(ret8)
#'{n,m}' 匹配前一个字符n到m次
ret9 = re.findall('hel{1,6}o','hellllllo world helloworld,world ello')
print(ret9)
#结论: *等于{0,正无穷} +等价于{1,+oo} ?等价于{0,1}
#[]字符集: 取消元字符的特殊功能(\ ^ -)
print("10")
ret10 = re.findall('[a-z]','hellllllo world helloworld,world ello')
print(ret10)
ret11 = re.findall('[w,*,.]','ww*aaassss..')
print(ret11)
ret12 = re.findall('[1-9,a-z,A-Z]','12323dgdgdg44445GGGGddLLL')
print(ret12)
#^放在[]里:取反
ret13 = re.findall('^iu','iu3535335353')
ret14 = re.findall('[^3,5]','iu3535335353')
print(ret13)
print(ret14)
# '\' 反斜杠后边跟元字符去除特殊功能
# 反斜杠后边跟普通字符实现特殊功能
#'\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的
#'\Z' 匹配字符结尾,同$
#'\d' 匹配数字0-9
#'\D' 匹配非数字
#'\w' 匹配[A-Za-z0-9]
#'\W' 匹配非[A-Za-z0-9]
#'s' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t'
#\b 匹配一个特殊边界,也就是指单词和空格间的位置
print(re.findall('\d{5}','fauisddallddg3535353535y4rt'))
print(re.findall('\sasd','fak asd'))
print(re.findall('\w','fak 111asd'))
print(re.findall(r'I\b','hello,I am a list!'))
#############search#############
#匹配出第一个满足条件的结果
print(re.search('sb','ffasbsfsfsb'))
print(re.search('sb','ffasbsfsfsb').group())
print(re.search('a\.','a.gj').group())
########################
print(re.findall(r'\\de','abc\de'))
####################() |###################
print(re.search('(as)+','sdddasasdddd').group())
print(re.search('(as)|3','sdddas3asdddd').group())
set15 = re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city")
print(set15)
################match################
print(re.match('asd','asddsgg asd').group())
###############split##############
print(re.split('a','dadsasdddd'))
print(re.split('[j,s]','djkslllasssl'))
###############sub##################
print(re.sub('a..x','s..b','sffafafaaaasfx sbssssbsssb'))

浙公网安备 33010602011771号