python学习之路day05

本节大纲:

  1. 模块介绍
  2. time &datetime模块
  3. random
  4. os
  5. sys
  6. shutil
  7. json & picle
  8. shelve
  9. xml处理
  10. yaml处理
  11. configparser
  12. hashlib
  13. subprocess
  14. logging模块
  15. re正则表达式

1.模块

1.1定义:用来从逻辑上组织python代码(变量,函数,类,逻辑:实现一个功能),本质就是.py结尾的python文件(文件名:test.py)

注:包的定语:本质就是一个目录(必须带一个_init_.py文件)。用来从逻辑上组织模块。

1.2.导入方法:

import module_test

import module_test,module_test1,module_test2

from module_test  import *(这个方法可忽略)

from module_test  import m1,m2,m3

from module_test import logger as  logger_alex

1.3impot本质(路径搜索和搜索路径)

导入模块的本质就是把python文件解释一遍

import module_test---->imodule_test。py------>imodule_test.py的路径---->sys.path(搜索路径)

导入包的本质就是执行该包下的_init_.py文件

1.4导入优化

rom module_test  import m1

1.5模块的分类

a.标准库

b.开源模块

c.自定义模块

标准库:

2.time与datetime

4 import time 5 
7 # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
8 # print(time.altzone) #返回与utc时间的时间差,以秒计算\
9 # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
10 # print(time.localtime()) #返回本地时间 的struct time对象格式
11 # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
13 # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
14 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
18 # 日期字符串 转成 时间戳
19 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
20 # print(string_2_struct)
21 # #
22 # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
23 # print(struct_2_stamp)
27 #将时间戳转为字符串格式
28 # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
29 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式

3.random模块

3.1随机数
import random
print random.random()
print random.randint( 1 , 2 )
print random.randrange( 1 , 10 )
3.2生成随机码
import random
checkcode = ''
for i in range ( 4 ):
     current = random.randrange( 0 , 4 )
     if current ! = i:
         temp = chr (random.randint( 65 , 90 ))
     else :
         temp = random.randint( 0 , 9 )
     checkcode + = str (temp)
print checkcode
4.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所指向的文件或者目录的最后修改时间
5.sys模块
sys.argv           命令行参数 List ,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit( 0 )
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的 Int
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
sys.stdout.write( 'please:' )
val = sys.stdin.readline()[: - 1 ]
6.shutil 模块
直接参考 http://www.cnblogs.com/wupeiqi/articles/4963027.html 
7.json & pickle 模块

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

8.xml处理模块

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

xml的格式如下,就是通过<>节点来区别数据结构的:

import xml.etree.ElementTree as ET
 
tree = ET.parse( "xmltest.xml" )
root = tree.getroot()
print (root.tag)
 
#遍历xml文档
for child in root:
     print (child.tag, child.attrib)
     for i in child:
         print (i.tag,i.text)
 
#只遍历year 节点
for node in root. iter ( 'year' ):
     print (node.tag,node.text)
修改XML
import xml.etree.ElementTree as ET
 
tree = ET.parse( "xmltest.xml" )
root = tree.getroot()
#修改
for node in root. iter ( 'year' ):
     new_year = int (node.text) + 1
     node.text = str (new_year)
     node. set ( "updated" , "yes" )
 
tree.write( "xmltest.xml" )
 
#删除node
for country in root.findall( 'country' ):
    rank = int (country.find( 'rank' ).text)
    if rank > 50 :
      root.remove(country)
tree.write( 'output.xml' )

9.hashlib模块  

用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

import hashlib
 
m = hashlib.md5()
m.update(b "Hello" )
m.update(b "It's me" )
print (m.digest())
m.update(b "It's been a long time since last time we ..." )
 
print (m.digest()) #2进制格式hash
print ( len (m.hexdigest())) #16进制格式hash
'''
def digest(self, *args, **kwargs): # real signature unknown
     """ Return the digest value as a string of binary data. """
     pass
 
def hexdigest(self, *args, **kwargs): # real signature unknown
     """ Return the digest value as a string of hexadecimal digits. """
     pass
 
'''
import hashlib
 
# ######## md5 ########
 
hash = hashlib.md5()
hash .update( 'admin' )
print ( hash .hexdigest())
# ######## sha1 ########
hash = hashlib.sha1()
hash .update( 'admin' )
print ( hash .hexdigest())
# ######## sha256 ########
hash = hashlib.sha256()
hash .update( 'admin' )
print ( hash .hexdigest())
 
# ######## sha384 ########
hash = hashlib.sha384()
hash .update( 'admin' )
print ( hash .hexdigest())
# ######## sha512 ########
hash = hashlib.sha512()
hash .update( 'admin' )
print ( hash .hexdigest())
注:更多关于md5,sha1,sha256等介绍的文章看这里https://www.tbs-certificates.co.uk/FAQ/en/sha256.html 
10.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'
 
'(?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' }
 
最常用的匹配方法
re.match 从头开始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符当做列表分隔符
re.sub      匹配字符并替换
仅需轻轻知道的几个匹配模式
re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
M(MULTILINE): 多行模式,改变 '^' '$' 的行为(参见上图)
S(DOTALL): 点任意匹配模式,改变 '.' 的行为
 
本节课作业

开发一个简单的python计算器

  1. 实现加减乘除及拓号优先级解析
  2. 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式(不能调用eval等类似功能偷懒实现),运算后得出结果,结果必须与真实的计算器所得出的结果一致

猜你喜欢

转载自www.cnblogs.com/0818and0119/p/9992909.html
今日推荐