python3模块

一、time模块

三种时间表示方式:

  • 时间戳:时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
  • 元组(struct_time):struct_time元组共有9个元素(年,月,日,时,分,秒,星期几,一年中第几天,夏令时)
  • 格式化的时间字符串
1.时间戳(单位:s)
import time
print(time.time())            
#返回:1537326837.3013458

2.结构化时间(年,月,日,时,分,秒,星期几,一年中第几天,夏令时)
2.1 当地时间
import time
print(time.localtime())            
#返回:time.struct_time(tm_year=2018, tm_mon=9, tm_mday=19, tm_hour=11, tm_min=16, tm_sec=4, tm_wday=2, tm_yday=262, tm_isdst=0)

2.2 世界标准时间(UTC)
import time
print(time.gmtime())
#返回:time.struct_time(tm_year=2018, tm_mon=9, tm_mday=19, tm_hour=3, tm_min=18, tm_sec=15, tm_wday=2, tm_yday=262, tm_isdst=0)

2.3 将结构化时间转换成时间戳
import time
print(time.mktime(time.localtime()))
#返回:1537327235.0

3.字符串时间
3.1 将结构化时间转换成字符串时间
import time
print(time.strftime('%Y.%m.%d %X',time.localtime()))
#返回:2018.09.19 11:23:32

3.2 将字符串时间转换成结构化时间
import time
print(time.strptime('2018-09-18 12:30:00','%Y-%m-%d %X'))
#返回:time.struct_time(tm_year=2018, tm_mon=9, tm_mday=18, tm_hour=12, tm_min=30, tm_sec=0, tm_wday=1, tm_yday=261, tm_isdst=-1)

4.astime()和ctime()
print(time.asctime())
print(time.ctime())
#返回:
Wed Sep 19 11:30:18 2018
Wed Sep 19 11:30:18 2018

5.datetime模块
import datetime
print(datetime.datetime.now())
#返回:2018-09-19 11:31:24.733255

二、random模块

1. 常用的方法

import random

(1)random.random()            #随机生成1个(0,1)之间的浮点数

(2)random.randint(1,5)            #随机生成1个[0,5]之间的整数

(3)random.randrange(1,3)            #随机生成1个[1,3)之间的整数

(4)random.choice([1,2,3,4,[5,6]])            #随机生成列表内的1个元素            

(5)random.sample([1,3,7,[6,8],9],3)            #随机生成列表内的3个元素

(6)random.uniform(1,6)            #随机生成1个(1,6)之间的浮点数

(7)list = ['a','b','c',6,8]
random.shuffle(list)            #将列表内元素的顺序重新排序
print(list)
#返回:[6, 'b', 8, 'c', 'a']

2. 随机生成四位验证码 

import random

def v_code():
    ret = ''
    for i in range(4):
        num = random.randint(0, 9)
        alf1 = chr(random.randint(65, 90))
        alf2 = chr(random.randint(97,122))
        s1 = random.choice([alf1,alf2])
        s2 = str(random.choice([num, s1]))
        ret += s2
    return ret


res = v_code()
print(res)

三、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下为"\r\n",Linux下为"\n"
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
os.path.join(path1, path2)        将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path)            返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)            返回path所指向的文件或者目录的最后修改时间

四、sys模块

1. 常用的方法

sys.argv           命令行参数List,第一个元素是程序本身路径

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

sys.version        获取Python解释程序的版本信息

sys.maxsize        最大的Int值

sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

sys.platform       返回操作系统平台名称

2. 显示进度条

import sys
import time
for i in range(100):
    sys.stdout.write('#')
    time.sleep(0.3)
    sys.stdout.flush()

五、json模块

什么是序列化?

我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等。

序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。

反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。

(1)json.dumps(把数据转换成json字符串)
import json
dic = {'time':'today'}
j = json.dumps(dic)
f = open('pkq','w')
f.write(j)
f.close()

(2)json.loads(提取原来的数据类型)
import json
f = open('pkq')
data = json.loads(f.read())

(3)json.dump
import json
f = open('pkc2')
dic = {'time':'today'}            
json.dump(dic,f)            #相当于:j = json.dumps(dic);f.write(j)
f.close()

(4)json.load
import json
f = open('pkc2')
data = json.load(f)         #相当于:data = json.loads(f.read())        

六、pickle模块

(1)pickle.dumps(把数据转换成pickle字符串)
import pickle
dic = {'name':'th'}
data = pickle.dumps(dic)
print(type(data))
# 返回:<class 'bytes'>

f = open('pkq3','wb')
f.write(data)


(2)pickle.loads(提取原来的数据类型)
import pickle
f = open('pkq3','rb')
data = pickle.loads(f.read())


(3)pickle.dump
import pickle
dic = {'name':'th'}
f = open('pkq4','wb')
pickle.dump(dic,f)            #相当于:data = pickle.dumps(dic);f.write(data)


(4)pickle.load
import pickle
f = open('pkq4','rb')
data = pickle.load(f)         #相当于:data = pickle.loads(f.read())

七、xml模块

1. xml数据格式

# 创建后缀为xml格式的文件
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

2. 用python操作xml

import xml.etree.ElementTree as ET

tree = ET.parse('C:/Users/Administrator/PycharmProjects/python_s3/D2/xmltext')
root = tree.getroot()
print(root.tag)

# 遍历xml文档
for i in root:
    print(i.tag, i.attrib)
    for j in i:
        print(j.tag, j.attrib, j.text)

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

# 修改操作:
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set('updated', 'yes')
tree.write('xmltext.xml')

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

3. 自己创建xml文档

import xml.etree.ElementTree as ET

new_xml = ET.Element('shoppinglist')
kind1 = ET.SubElement(new_xml, 'kind1', attrib={'food':'noodle'})
color = ET.SubElement(kind1, 'color', attrib={'color':'white'})
price = ET.SubElement(kind1, 'price',attrib={'price':'$5'})
kind2 = ET.SubElement(new_xml, 'kind2', attrib={'food':'water'})
color = ET.SubElement(kind2, 'color', attrib={'color':'yellow'})
price = ET.SubElement(kind2, 'price',attrib={'price':'$1'})

et = ET.ElementTree(new_xml)            #生成文档对象
et.write("new_xml.xml", encoding="utf-8",xml_declaration=True)
ET.dump(new_xml)                        #打印生成的格式

八、re模块

1. 两种字符形式:

1.1 普通字符:字母、数字、其他特殊符号等。

1.2 元字符:. $ * + ? {} [] | () \

import re

1.2.1 通配符. 
ret = re.findall('m.y..','mayun')
print(ret)    #['mayun']

1.2.2 从开头匹配^
ret = re.findall('^ma','mayunma')
print(ret)    #['ma']

1.2.3 从结尾匹配$
ret = re.findall('m.$','huamayunma')
print(ret)    #['ma']

1.2.4 匹配重复字符* (贪婪匹配[0,+∞])
ret = re.findall('ma*','maaaaam')
print(ret)    #['maaaaa', 'm']

1.2.5 匹配重复字符+ ([1,+∞])
ret = re.findall('ma+','maaaaam')
print(ret)    #['maaaaa']

1.2.6 匹配重复字符? ([0,1])
ret = re.findall('ma?','maaaaam')
print(ret)    #['ma', 'm']

1.2.7 匹配重复字符{} (自行规定范围)
ret = re.findall('ma{3}','maaaaam')
print(ret)    #['maaa']
# 注:在以上四个符号后面加?可使其变为惰性匹配
# ret = re.findall('ma+?','maaaaam')
# print(ret)  #['ma']
1.2.8 字符集[]
import re

ret = re.findall('a[bc]d', 'abdacd')
print(ret)    #['abd', 'acd']

ret = re.findall('[.*+]', 'a.cd+')
print(ret)    #['.', '+']
# 注:字符集里的元字符不具有特殊意义

…………………………………………………………………………………………………………………………………………………………………………………………………………………………………………

# 在字符集里有功能的符号:- ^ \

# 范围-
ret1 = re.findall('[a-z]', 'abcasdasfdsaf')
print(ret1)   #['a', 'b', 'c', 'a', 's', 'd', 'a', 's', 'f', 'd', 's', 'a', 'f']
ret2 = re.findall('q[a-z]*','asdqadsfsdfadsf6')
print(ret2)   #['qadsfsdfadsf']

# 非^
ret = re.findall('[^123]','asasd14335435')
print(ret)    #['a', 's', 'a', 's', 'd', '4', '5', '4', '5']

# 转义\
ret = re.findall('[\d]','123abc')
print(ret)    #['1', '2', '3']

## 转义符补充
反斜杠\后跟元字符:去除特殊功能
反斜杠\后跟普通字符:实现特殊功能
# 例:
\d 匹配任何十进制数,相当于类[0-9]
\D 匹配任何非数字字符,相当于类[^0-9]
\s 匹配任何空白字符,相当于类[\t \n \r \f \v]
\S 匹配任何非空白字符,相当于类[^\t \n \r \f \v]
\w 匹配任何字母和数字字符,相当于类[a-z,A-Z,0-9]
\W 匹配任何非字母和非数字字符,相当于类[^a-z,A-Z,0-9]
\b 匹配特殊字符边界,比如空格,&,#等
1.2.9 分组()
import re

ret = re.findall('(abc)+','(abc)(abc)(abc)')
print(ret)                #['abc', 'abc', 'abc']

ret = re.search('(?P<name>[a-z]+)(?P<age>\d+)','th23')
print(ret.group())        #th23
print(ret.group('name'))  #th


# findall会优先匹配组里的内容,如果想匹配全部结果,需取消权限
ret = re.findall('www\.(baidu|google)\.com','qwerwww.google.comnice')
print(ret)                #['google']    

ret = re.findall('www\.(?:baidu|google)\.com','qwerwww.google.comnice')
print(ret)                #['www.google.com']
1.2.10 或|
import re

ret = re.findall('ab|cd|e','adcderyu')
print(ret)                #['cd', 'e']        

 2. 常用的方法

# findall 返回所有满足匹配条件的结果,放在列表里
ret = re.findall('th','mayunth')
print(ret)                #['th']

# search 找到第一个匹配,然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有被匹配到,返回None
ret = re.search('th','aaathmayunth').group()
print(ret)                #th            

# match 同search功能,但从字符串开始处进行匹配 
ret = re.match('t','tht').group()
print(ret)                #t 

# split 分割
ret = re.split('[ac]','abcd')
print(ret)                #['', 'b', 'd']

# sub和subn 替换
ret = re.sub('\d+','china','19491001 establish 19491001',1)
print(ret)            #china establish 19491001
ret = re.subn('\d+','china','19491001 establish 19491001')
print(ret)                #('china establish china', 2)

# compile 制定规则
rule = re.compile('\d+')
ret = rule.search('20181001cqitd')
print(ret.group())        #20181001

# finditer
ret = re.finditer('\d+','123456abc789')
print(ret)                #<callable_iterator object at 0x00000000006D9F60>           
print(next(ret).group())  #123456
print(next(ret).group())  #789     

九、logging模块

1. 日志级别

(1)debug
(2)info
(3)warning
(4)error
(5)critical

2. 配置日志级别,日志格式,输出位置

# 在屏幕上打印日志信息
import logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(filename)s line:%(lineno)d %(levelname)s %(message)s',
    # filename='log',
    # filemode='w')    

logging.debug('ok')
logging.info('someok')
logging.warning('someno')
logging.error('manyno')
logging.critical('no')

# 不在屏幕上打印日志信息,但会生成文件名为log的日志文件
import logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(filename)s line:%(lineno)d %(levelname)s %(message)s',
    filename='log',
    filemode='w')

logging.debug('ok')        #2018-10-09 20:14:03,286 loggingtest.py line:9 DEBUG ok            
logging.info('someok')     #2018-10-09 20:14:03,287 loggingtest.py line:10 INFO someok
logging.warning('someno')  #2018-10-09 20:14:03,287 loggingtest.py line:11 WARNING someno
logging.error('manyno')    #2018-10-09 20:14:03,287 loggingtest.py line:12 ERROR manyno
logging.critical('no')     #2018-10-09 20:14:03,287 loggingtest.py line:13 CRITICAL no
# 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 字符串形式的当前时间。默认格式是 “2018-10-08 11:45:15,981”。逗号后面的是毫秒
%(thread)d 线程ID
%(threadName)s 线程名
%(process)d 进程ID
%(message)s 用户输出的消息

猜你喜欢

转载自blog.csdn.net/maergaiyun/article/details/82768754