Python打卡第五周

Posted yuanjun93

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python打卡第五周相关的知识,希望对你有一定的参考价值。

 

time模块

>>> print(time.altzone())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int object is not callable
>>> print(time.altzone)
-32400
>>> print(time.asctime())
Tue May  7 16:59:41 2019
>>> print(time.localtime())
time.struct_time(tm_year=2019, tm_mon=5, tm_mday=7, tm_hour=17, tm_min=0, tm_sec=20, tm_wday=1, tm_yday=127, tm_isdst=0)
>>> print(time.gmtime(time.time()-800000))
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=28, tm_hour=2, tm_min=47, tm_sec=30, tm_wday=6, tm_yday=118, tm_isdst=0)
>>> print(time.ctime())
Tue May  7 17:01:29 2019
>>> string_2_struct = time.strptime("2019/05/07","%Y/%m/%d")
>>> print(string_2_struct)
time.struct_time(tm_year=2019, tm_mon=5, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=127, tm_isdst=-1)
>>> struct_2_stamp = time.mktime(string_2_struct)
>>> print(struct_2_stamp)
1557158400.0
>>> print(time.gmtime(time.time()-86640))
time.struct_time(tm_year=2019, tm_mon=5, tm_mday=6, tm_hour=9, tm_min=35, tm_sec=13, tm_wday=0, tm_yday=126, tm_isdst=0)
>>> print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))
2019-05-07 09:40:16

 

datetime模块(时间加减)

>>> import datetime
>>> print(datetime.datetime.now())
2019-05-07 17:43:05.423388
>>> print(datetime.date.fromtimestamp(time.time()))
2019-05-07
>>> print(datetime.datetime.now()+datetime.timedelta(3))
2019-05-10 17:44:42.488463
>>> print(datetime.datetime.now()+datetime.timedelta(-3))
2019-05-04 17:44:57.456037
>>> print(datetime.datetime.now()+datetime.timedelta(hours=3))
2019-05-07 20:45:08.262508
>>> print(datetime.datetime.now()+datetime.timedelta(minutes=30))
2019-05-07 18:15:21.419263
>>> c_time = datetime.datetime.now()
>>> print(c_time.replace(minute=3,hour=2) )
2019-05-07 02:03:35.778493

 

Commonly used format codes:

        %Y  Year with century as a decimal number.
        %m  Month as a decimal number [01,12].
        %d  Day of the month as a decimal number [01,31].
        %H  Hour (24-hour clock) as a decimal number [00,23].
        %M  Minute as a decimal number [00,59].
        %S  Second as a decimal number [00,61].
        %z  Time zone offset from UTC.
        %a  Locales abbreviated weekday name.
        %A  Locales full weekday name.
        %b  Locales abbreviated month name.
        %B  Locales full month name.
        %c  Locales appropriate date and time representation.
        %I  Hour (12-hour clock) as a decimal number [01,12].
        %p  Locales equivalent of either AM or PM.

 

random模块

>>> import random
>>> print(random.random())#随机一个0-1之间的数
0.37793433766068685
>>> print(random.randint(1,2))#[1,2)
1
>>> print(random.randrange(1,10))#[1,10)
7

 

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所指向的文件或者目录的最后修改时间

 

sys模块

sys.argv           #命令行参数List,第一个元素是程序本身路径
sys.exit(n)        #退出程序,正常退出时exit(0)
sys.version        #获取Python解释程序的版本信息
sys.path           #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform      # 返回操作系统平台名称
sys.stdout.write(please:)
val = sys.stdin.readline()[:-1] #返回值为-1

 

shutil模块

import shutil

f1 = open("本节笔记.txt",encoding="utf-8")

f2 = open("笔记2","w",encoding="utf-8")

shutil.copyfileobj(f1,f2)  #将文件内容拷贝到另一个文件中,可以部分内容

shutil.copyfile("笔记2","笔记3")  #拷贝文件

shutil.copystat("本节笔记.txt","笔记3")#修改时间跟访问时间被修改

shutil.copytree("test4","new_test4")#递归复制
shutil.rmtree("new_test4")#递归删除

shutil.make_archive("shutil_test","zip","E:\All Day\Day5")  #将当前文件夹添加到压缩包内

 

zipfile模块

#压缩

import zipfile#单独一个一个的压。用这个好使
z = zipfile.ZipFile("Day5.zip","w")
z.write("本节笔记.txt")
print("------")
z.write("p_test.py")
z.close()


#解压
z = zipfile.ZipFile(Day5.zip, r) z.extractall() z.close()

 

shelve模块

import shelve
import datetime
d = shelve.open("shelve_test")

name = ["louis","rain","test"]

info = {age:18,"name":louis}

d["name"] = name#持久化列表
d["info"] = info#持久dict
d[data] = datetime.datetime.now()

print(d.get("name"))
print(d.get("info"))
print(d.get("date"))

d.close()

 

xml处理模块

xml的格式

<?xml version="1.0"?>
<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>

 

通过Python进行处理xml

import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot()
# print(root)
print(root.tag)  #tag是标签名字

# 遍历xml文档
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag, i.text , i.attrib) #标签,文本,属性

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

 

通过Python修改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_by", "louis")

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)

 

xml的创建

mport xml.etree.ElementTree as ET

new_xml = ET.Element("personinfolist")
personinfo = ET.SubElement(new_xml, "personinfo", attrib={"enrolled": "yes"})
age = ET.SubElement(personinfo, "age", attrib={"checked": "no"})
name = ET.SubElement(personinfo, "name")
name.text = "louis"

sex = ET.SubElement(personinfo, "sex")
sex.text = "man"
age.text = 18
personinfo2 = ET.SubElement(new_xml, "personinfo", attrib={"enrolled": "no"})
age = ET.SubElement(personinfo2, "age")
name = ET.SubElement(personinfo2, "name")
name.text = "Jack"
age.text = 33

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

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

 

ConfigParser模块

import configparser #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)

 

运行结果

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no

 

读configparser文件

import configparser

conf = configparser.ConfigParser()

conf.read("example.ini")

# print(conf.sections())
print(conf.defaults())

print(conf[bitbucket.org][user])

sec = conf.remove_section(bitbucket.org)
conf.write(open(exmple2.cfg,"w"))

 

hashlib模块

import hashlib
 
m = hashlib.md5()
m.update(b"Hello")
m.update(b"It‘s me")
print(m.hexdigest())  #两句等于“HelloIt‘s me”
# ######## 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())

 

hmac模块

import hmac

h = hmac.new("天王盖地虎".encode(encoding="utf-8"),"宝塔镇河妖".encode(encoding="utf-8"))
print(h.hexdigest())

 

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打卡第五周的主要内容,如果未能解决你的问题,请参考以下文章

python学习--第五周

python第五周,函数的定义与使用,代码复用与函数递归

python-爬取中国大学排名(第五周)

python第五周学习内容

python周报第五周

python第五周,Pylnstaller库的使用,科赫雪花小包裹