python模块汇总练习
模块练习
1、random模块
# print(random.random()) # print(random.randint(1,3)) #模拟随机验证码 def make_code(n=5): res='' for i in range(n): s1=str(random.randint(0,9)) s2=chr(random.randint(65,90)) res+=random.choice([s1,s2]) return res print(make_code(10))
2、模拟打印进度条
1 num=30 2 print('%s%%'%num) 3 4 #打印进度条 5 width=50 6 print(('[%%-%ds]'%width)%'#') 7 print(('[%%-%ds]'%width)%'##') 8 print(('[%%-%ds]'%width)%'###') 9 print(('[%%-%ds]'%width)%'####') 10 11 def progress(percent,width=50): 12 if percent > 1: 13 percent=1 14 show_str=(('[%%-%ds]'%width)%(int(width*percent)* '#')) 15 print('\r%s %d%%'%(show_str,int(100*percent)),end=' ') 16 17 import time,random 18 recv_size=0 19 total_size=8097 20 while recv_size<total_size: 21 time.sleep(0.5) 22 recv_size+=1024 23 percent=recv_size / total_size 24 progress(percent)
3、shelve模块(序列化)
1 import shelve 2 3 #序列化 4 info1={'age':18,'herght':180,'weight':80} 5 info2={'age':88,'herght':150,'weight':80} 6 7 d=shelve.open('db.shv') 8 d['egon']=info1 9 d['alex']=info2 10 d.close() 11 12 #反序列化 13 d=shelve.open('db.shv') 14 print(d['alex']) 15 print(d['egon']) 16 d.close() 17 18 19 #修改数据 20 d=shelve.open('db.shv',writeback=True) 21 # d['alex']['age']=10000 22 print(d['alex']) 23 d.close()
4、xml模块
1 import xml.etree.ElementTree as ET 2 tree=ET.parse('a.xml') 3 root=tree.getroot() 4 5 #========================================》》查 6 #三种方式查找节点 7 res=root.iter('rank')#会在整个树中进行查找,而且是查找所有 8 for item in res: 9 # print(item) 10 print('='*50) 11 print(item.tag)#标签名 12 print(item.attrib)#属性 13 print(item.text)#文本内容 14 15 16 res=root.find('country')#只能在当前元素的下一级进行查找,并且只找到一个就截止 17 # print(res.tag) 18 # print(res.attrib) 19 # print(res.text) 20 n=res.find('rank') 21 print(n.attrib) 22 23 24 25 res=root.findall('country')#只能在当前元素的下一级进行查找, 26 print([item.tag for item in res]) 27 28 29 30 #=====================================》》改 31 import xml.etree.ElementTree as ET 32 tree=ET.parse('a.xml') 33 root=tree.getroot() 34 35 for year in root.iter('year'): 36 year.text=str(int(year.text)+10) 37 year.attrib={'updated':'yes'} 38 tree.write('a.xml') 39 40 41 42 #===============================》增 43 import xml.etree.ElementTree as ET 44 tree=ET.parse('a.xml') 45 root=tree.getroot() 46 47 for country in root.iter('country'): 48 # print('year') 49 year=country.find('year') 50 # print(year) 51 if int(year.text) > 2010: 52 # print(country.attrib) 53 # ele=ET.Element('egon') 54 # ele.attrib={'nb':'yes'} 55 # ele.text='好' 56 # country.append(ele) 57 country.remove(year) 58 59 tree.write('b.xml')
2018-08-15 22:54:40