python常用模块(二)
生活随笔
收集整理的這篇文章主要介紹了
python常用模块(二)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
configparser模塊
學習python中有什么不懂的地方,小編這里推薦加小編的python學習群:895 817 687有任何不懂的都可以在里面交流,還有很好的視頻教程pdf學習資料,大家一起學習交流!
用于生成和修改常見配置文檔
配置文件
[default] serveraliveinterval = 45 compression = yes compressionlevel = 9[bitbucket.org] user = hg[topsecret.server.com] port = 50022 forwardx11 = no用python生成這樣的一個配置文檔
import configparserconfig = configparser.ConfigParser() config['default'] = {'ServerAliveInterval':'45','Compression':'yes','CompressionLevel':'9'}config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg'config['topsecret.server.com'] = {'port':'50022','Forwardx11':'no'}with open('example.ini','w') as configfile:config.write(configfile)讀取
import configparserconfig = configparser.ConfigParser() print(config.read('example.ini'))#查看所有的標題 print(config.sections()) #['default', 'bitbucket.org', 'topsecret.server.com']#查看標題section1下所有key=value的key options = config.options('default') print(options) #['serveraliveinterval', 'compression', 'compressionlevel']#查看標題section1下所有key=value的(key,value)格式 items_list = config.items('topsecret.server.com') print(items_list) #[('port', '50022'), ('forwardx11', 'no')]增刪改查
import configparserconfig = configparser.ConfigParser() config.read('example.ini',encoding = 'utf-8')#刪除整個標題 config.remove_section('bitbucket.org')#刪除標題下的option config.remove_option('topsecret.server.com','port')#添加一個標題 config.add_section('info') #在標題下添加options config.set('info','name','derek')#判斷是否存在 print(config.has_section('info')) #True print(config.has_option('info','name')) #True#將修改的內容存入文件 config.write(open('new_example.ini','w')) #修改后的文件[default] serveraliveinterval = 45 compression = yes compressionlevel = 9[topsecret.server.com] forwardx11 = no[info] name = derekhashlib模塊
hash:一種算法 ,3.x里代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法 三個特點: 1.內容相同則hash運算結果相同,內容稍微改變則hash值則變 2.不可逆推 3.相同算法:無論校驗多長的數據,得到的哈希值長度固定。 1 import hashlib23 m=hashlib.md5()# m=hashlib.sha256()45 m.update('hello'.encode('utf8'))6 print(m.hexdigest()) #5d41402abc4b2a76b9719d911017c59278 m.update('alvin'.encode('utf8'))9 10 print(m.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af 11 12 m2=hashlib.md5() 13 m2.update('helloalvin'.encode('utf8')) 14 print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af 15 16 ''' 17 注意:把一段很長的數據update多次,與一次update這段長數據,得到的結果一樣 18 但是update多次為校驗大文件提供了可能。re模塊
# 正則匹配 import re# \w與\W 字母數字下劃線 print(re.findall('\w', 'hello derek \n 123')) print(re.findall('\W', 'hello derek \n 123')) # ['h', 'e', 'l', 'l', 'o', 'd', 'e', 'r', 'e', 'k', '1', '2', '3'] # [' ', ' ', '\n', ' ']# \s與\S 匹配任意空白字符 print(re.findall('\s', 'hello egon 123')) # [' ', ' ', ' ', ' '] print(re.findall('\S', 'hello egon 123')) # ['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']# \n \t都是空,都可以被\s匹配 print(re.findall('\s', 'hello \n egon \t 123')) # [' ', '\n', ' ', ' ', '\t', ' ']# \n與\t print(re.findall(r'\n', 'hello egon \n123')) # ['\n'] print(re.findall(r'\t', 'hello egon\t123')) # ['\n']# \d與\D print(re.findall('\d', 'hello egon 123')) # ['1', '2', '3'] print(re.findall('\D', 'hello egon 123')) # ['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']# \A與\Z \A 匹配字符串開始 \Z 匹配字符串結束 print(re.findall('\Ahe', 'hello egon 123')) # ['he'],\A==>^ print(re.findall('123\Z', 'hello egon 123')) # ['he'],\Z==>$# ^與$ print(re.findall('^h', 'hello egon 123')) # ['h'] print(re.findall('3$', 'hello egon 123')) # ['3']# 重復匹配:| . | * | ? | .* | .*? | + | {n,m} | # . 匹配任意字符,除了換行符,除非re.DOTALL標記 print(re.findall('a.b', 'a1b')) # ['a1b'] # a和b中間匹配任意一個字符 print(re.findall('a.b', 'a1b a*b a b aaab')) # ['a1b', 'a*b', 'a b', 'aab'] print(re.findall('a.b', 'a\nb')) # [] print(re.findall('a.b', 'a\nb', re.S)) # ['a\nb'] print(re.findall('a.b', 'a\nb', re.DOTALL)) # ['a\nb']同上一條意思一樣 print(re.findall('a...b', 'a123b')) # ['a123b']# *匹配*號前的字符0次或多次 print(re.findall('ab*', 'bbbbbbb')) # [] print(re.findall('ab*', 'a')) # ['a'] print(re.findall('ab*', 'abbbb')) # ['abbbb'] print(re.findall('ab*', 'abababbabbbb')) # ['ab', 'ab', 'abb', 'abbbb']# ? 匹配前一個字符1次或0次 print(re.findall('ab?', 'a')) # ['a'] print(re.findall('ab?', 'abbb')) # ['ab'] # 匹配所有包含小數在內的數字 print(re.findall('\d+\.?\d*', "asdfasdf123as1.13dfa12adsf1asdf3")) # ['123', '1.13', '12', '1', '3']# .*默認為貪婪匹配 print(re.findall('a.*b', 'a1b22222222b')) # ['a1b22222222b']# .*?為非貪婪匹配:推薦使用 print(re.findall('a.*?b', 'a1b22222222b')) # ['a1b']# + 匹配前一個字符1次或多次 print(re.findall('ab+', 'abbaabb')) # ['abb', 'abb'] print(re.findall('ab+', 'abbb')) # ['abbb']# {n,m} 匹配前一個字符n到m次 print(re.findall('ab{2}', 'abbb')) # ['abb'] print(re.findall('ab{2,4}', 'abbb')) # ['abb'] print(re.findall('ab{1,}', 'abbb')) # 'ab{1,}' ===> 'ab+' print(re.findall('ab{0,}', 'abbb')) # 'ab{0,}' ===> 'ab*'# [] print(re.findall('a[1*-]b', 'a1b a*b a-b')) # []內的都為普通字符了,且如果-沒有被轉意的話,應該放到[]的開頭或結尾 print(re.findall('a[^1*-]b', 'a1b a*b a-b a=b')) # []內的^代表的意思是取反,所以結果為['a=b'] print(re.findall('a[0-9]b', 'a1b a*b a-b a=b')) # []內的^代表的意思是取反,所以結果為['a=b'] print(re.findall('a[a-z]b', 'a1b a*b a-b a=b aeb')) # []內的^代表的意思是取反,所以結果為['a=b'] print(re.findall('a[a-zA-Z]b', 'a1b a*b a-b a=b aeb aEb')) # []內的^代表的意思是取反,所以結果為['a=b']# \# print(re.findall('a\\c','a\c')) #對于正則來說a\\c確實可以匹配到a\c,但是在python解釋器讀取a\\c時,會發生轉義,然后交給re去執行,所以拋出異常 print(re.findall(r'a\\c', 'a\c')) # r代表告訴解釋器使用rawstring,即原生字符串,把我們正則內的所有符號都當普通字符處理,不要轉義 print(re.findall('a\\\\c', 'a\c')) # 同上面的意思一樣,和上面的結果一樣都是['a\\c']# (): 匹配括號里面的內容 print(re.findall('ab+', 'ababab123')) # ['ab', 'ab', 'ab'] print(re.findall('(ab)+123', 'ababab123')) # ['ab'],匹配到末尾的ab123中的ab print(re.findall('(?:ab)+123', 'ababab123')) # findall的結果不是匹配的全部內容,而是組內的內容,?:可以讓結果為匹配的全部內容# | print(re.findall('compan(?:y|ies)', 'Too many companies have gone bankrupt, and the next one is my company'))一些方法
# ===========================re模塊提供的方法介紹=========================== import re #1 print(re.findall('e','alex make love') ) #['e', 'e', 'e'],返回所有滿足匹配條件的結果,放在列表里 #2 print(re.search('e','alex make love').group()) #e,只到找到第一個匹配然后返回一個包含匹配信息的對象,該對象可以通過調用group()方法得到匹配的字符串,如果字符串沒有匹配,則返回None。#3 print(re.match('e','alex make love')) #None,同search,不過在字符串開始處進行匹配,完全可以用search+^代替match#4 print(re.split('[ab]','abcd')) #['', '', 'cd'],先按'a'分割得到''和'bcd',再對''和'bcd'分別按'b'分割#5 print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默認替換所有 print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===> love make alexprint('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),結果帶有總共替換的個數#6 obj=re.compile('\d{2}')print(obj.search('abc123eeee').group()) #12 print(obj.findall('abc123eeee')) #['12'],重用了objshelve模塊
shelve模塊比pickle模塊簡單,只有一個open函數,返回類似字典的對象,可讀可寫;key必須為字符串,而值可以是python所支持的數據類型
import shelvef=shelve.open(r'sheve.txt') # f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']} # f['stu2_info']={'name':'gangdan','age':53} # f['school_info']={'website':'http://www.pypy.org','city':'beijing'}print(f['stu1_info']['hobby']) f.close()logging模塊
很多程序都有記錄日志的需求,并且日志中包含的信息即有正常的程序訪問日志,還可能有錯誤、警告等信息輸出,python的logging模塊提供了標準的日志接口,你可以通過它存儲各種格式的日志,logging的日志可以分為 debug、info、warning、error、critical5個級別
1.模塊初始
import logginglogging.warning('wrong password more than 3 times') logging.critical('server is down') logging.error('error message')結果: WARNING:root:wrong password more than 3 times CRITICAL:root:server is down ERROR:root:error message2.logging模塊五個級別
總結
以上是生活随笔為你收集整理的python常用模块(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python常用模块(一)
- 下一篇: python进程\协程\异步IO