第四章: 4.1 logging模块 | 正则表达式
?
修改json數據然后寫入json文件中
f = open('1234.json','r',encoding='utf-8') data = f.read() data1 = json.loads(data)data1['status'] = 1f1 = open('1234.json','w',encoding='utf-8')json.dump(data1,f1)hashlib md5值的用法
#加入下面這個就可以 password = input('請輸入密碼:')m = hashlib.md5()m.update(password.encode())if m.hexdigest() == data1['password']:print('登錄成功')?
?configparser模塊
增刪該查
#修改時區 default-time-zone = '+8:00' 為 校準的全球時間 +00:00 import configparser config = configparser.ConfigParser() config.read('my.cnf') print(config['mysqld']['default-time-zone'] ) #08:00 config.set('mysqld','default-time-zone','+00:00') config.write(open('my.cnf', "w")) print(config['mysqld']['default-time-zone'] ) #+00:00刪除
##刪除 explicit_defaults_for_timestamp import configparser config = configparser.ConfigParser() config.read('my.cnf') config.remove_option('mysqld','explicit_defaults_for_timestamp') config.write(open('my.cnf', "w"))?
##為DEFAULT增加一條 character-set-server = utf8 import configparser config = configparser.ConfigParser() config.read('my.cnf') config.set('DEFAULT','character-set-server','utf8') config.write(open('my.cnf', "w"))?
13、logging模塊
?日志級別:DEBUG、INFO、WARNING、ERROR、CRITICAL。 ?debug是最低的內置級別,critical為最高
level=loggin.INFO意思是,把日志紀錄級別設置為INFO,也就是說,只有比日志是INFO或比INFO級別更高的日志才會被紀錄到文件里。
?
import logging# logging.basicConfig(filename='example.log',level=logging.INFO) #換成INFO,則不會記錄debug logging.basicConfig(filename='example.log',level=logging.DEBUG)#它會追加,不是覆蓋 logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too')example.log INFO:root:So should this WARNING:root:And this, too DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too?自定義日志格式
?
import logging logging.basicConfig(filename='example.log',level=logging.DEBUG,format='%(asctime)s:%(levelname)s:%(filename)s:%(funcName)s %(message)s', # %(asctime)s:是字符串形式的當前時間默認格式是 “2003-07-08 16:49:45,896”,逗號后面的是毫秒;%(levelname)s:文本形式的日志級別;%(funcName)s是函數的函數名;datefmt='%Y-%m-%d %I:%M:%S %p') def sayhi():logging.error("from sayhi....") sayhi()logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too') INFO:root:So should this WARNING:root:And this, too DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too 03/22/2018 11:54:58 PM This message should go to the log file 03/22/2018 11:54:58 PM So should this 03/22/2018 11:54:58 PM And this, too 2018-03-22 11:56:37 PM This message should go to the log file 2018-03-22 11:56:37 PM So should this 2018-03-22 11:56:37 PM And this, too 2018-03-22 11:58:08 PM-10- This message should go to the log file 2018-03-22 11:58:08 PM-20- So should this 2018-03-22 11:58:08 PM-30- And this, too 2018-03-23 12:02:08 AM:DEBUG:C:/Users/Administrator/PycharmProjects/myFirstpro/chapter4?���??/logging_mode.py This message should go to the log file 2018-03-23 12:02:08 AM:INFO:C:/Users/Administrator/PycharmProjects/myFirstpro/chapter4?���??/logging_mode.py So should this 2018-03-23 12:02:08 AM:WARNING:C:/Users/Administrator/PycharmProjects/myFirstpro/chapter4?���??/logging_mode.py And this, too 2018-03-23 12:05:42 AM:DEBUG:logging_mode.py:logging_mode This message should go to the log file 2018-03-23 12:05:42 AM:INFO:logging_mode.py:logging_mode So should this 2018-03-23 12:05:42 AM:WARNING:logging_mode.py:logging_mode And this, too 2018-03-23 12:06:04 AM:ERROR:logging_mode.py:logging_mode from sayhi.... 2018-03-23 12:06:04 AM:DEBUG:logging_mode.py:logging_mode This message should go to the log file 2018-03-23 12:06:04 AM:INFO:logging_mode.py:logging_mode So should this 2018-03-23 12:06:04 AM:WARNING:logging_mode.py:logging_mode And this, too 2018-03-23 12:07:12 AM:ERROR:logging_mode.py:sayhi from sayhi.... 2018-03-23 12:07:12 AM:DEBUG:logging_mode.py:<module> This message should go to the log file 2018-03-23 12:07:12 AM:INFO:logging_mode.py:<module> So should this 2018-03-23 12:07:12 AM:WARNING:logging_mode.py:<module> And this, too?
日志同時輸出到屏幕和文件
Python 使用logging模塊記錄日志涉及四個主要類,使用官方文檔中的概括最為合適:
- logger提供了應用程序可以直接使用的接口;
- handler將(logger創建的)日志記錄發送到合適的目的輸出;
- filter提供了細度設備來決定輸出哪條日志記錄;
- formatter決定日志記錄的最終輸出格式。
?
過濾 filter組件
如果你想對日志內容進行過濾,就可自定義一個filter;
注意filter函數會返加True or False,logger根據此值決定是否輸出此日志
然后把這個filter添加到logger中;?logger.addFilter(IgnoreBackupLogFilter())
import loggingclass IgnoreBackupLogFilter(logging.Filter):"""忽略帶db backup 的日志"""def filter(self, record): #固定寫法; 把日志對象傳進來。return "db backup" not in record.getMessage() #它不在就會返回; "db backup" not in "test log" 就返回true; "db backup" not in "test log db backup"就返回false #1.生成logger對象 logger =logging.getLogger("web") logger.setLevel(logging.DEBUG) #設置下級別 #這個是全局的 #1.1把filter對象添加到logger中 logger.addFilter(IgnoreBackupLogFilter()) #這樣就支持過濾了# #2.生成handler對象 ch = logging.StreamHandler() fh = logging.FileHandler("web.log") # #2.1把handler對象綁定到logger logger.addHandler(ch) logger.addHandler(fh)# #3.生成formatter對象 # #3.1把formatter對象綁定handler對象 file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s- %(lineno)d- %(message)s')ch.setFormatter(console_formatter) fh.setFormatter(file_formatter)logger.warning("test log") logger.info("test log 2") logger.debug("test log 3") logger.debug("test log db backup 3") #屏幕上輸出 db backup 3不在里邊就返回true 然后就把它過濾掉 2018-06-11 16:22:04,120 - web - WARNING- 89- test log 2018-06-11 16:22:04,120 - web - INFO- 90- test log 2 2018-06-11 16:22:04,120 - web - DEBUG- 91- test log 3文件里邊輸出: 2018-06-11 16:22:04,120 - web - WARNING - test log 2018-06-11 16:22:04,120 - web - INFO - test log 2 2018-06-11 16:22:04,120 - web - DEBUG - test log 3?
文件自動截斷
按大小 制定了3個,再多了就會把最后邊的給刪了
import logging from logging import handlers class IgnoreBackupLogFilter(logging.Filter):"""忽略帶db backup 的日志"""def filter(self, record): #固定寫法return "db backup" in record.getMessage() # #1.生成logger對象 logger =logging.getLogger("web") logger.setLevel(logging.DEBUG) #設置下級別 #這個是全局的 #1.1把filter對象添加到logger中 logger.addFilter(IgnoreBackupLogFilter()) #這樣就支持過濾了# #2.生成handler對象 ch = logging.StreamHandler() fh = handlers.RotatingFileHandler("web_log",maxBytes=10,backupCount=3)#按照大小 #fh = handlers.TimedRotatingFileHandler("web_log",when="S",interval=5,backupCount=3) ##按照時間 # #2.1把handler對象綁定到logger logger.addHandler(ch) logger.addHandler(fh) # #3.生成formatter對象 # #3.1把formatter對象綁定handler對象 file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s- %(lineno)d- %(message)s') ch.setFormatter(console_formatter) fh.setFormatter(file_formatter) logger.warning("test log") logger.info("test log 2") logger.debug("test log 3") logger.debug("test log db backup 3")?
14、re正則表達式
?正則表達式就是字符串的匹配規則,在多數編程語言里都有相應的支持,python里對應的模塊是re
####文件 姓名 地區 身高 體重 電話 況詠蜜 北京 171 48 13651054608 王心顏 上海 169 46 13813234424 馬纖羽 深圳 173 50 13744234523 喬亦菲 廣州 172 52 15823423525 羅夢竹 北京 175 49 18623423421 劉諾涵 北京 170 48 18623423765 岳妮妮 深圳 177 54 18835324553 賀婉萱 深圳 174 52 18933434452 葉梓萱 上海 171 49 18042432324 杜姍姍 北京 167 49 13324523342 ############ f = open("兼職白領學生空姐模特護士聯系方式.txt",'r',encoding="utf-8") phones = [] for line in f:name,city,height,weight,phone = line.split()if phone.startswith('1') and len(phone) == 11:phones.append(phone) print(phones)?
import re f = open("兼職白領學生空姐模特護士聯系方式.txt",'r',encoding="utf-8") data = f.read() phones = re.findall("1[0-9]{10}",data) print(phones)?
re.match(從頭開始匹配);re.search(全局匹配);?re.findall()沒有索引,有幾個找幾個;
>>> import re >>> s = 'abc1d3e' >>> re.match('[0-9]',s) >>> print(re.match('[0-9]',s)) None >>> re.match('[0-9]','1bdfd') #只匹配一個,開頭的; <_sre.SRE_Match object; span=(0, 1), match='1'> >>> s 'abc1d3e' >>> re.search('[0-9]',s) #只匹配一個,全局查找; <_sre.SRE_Match object; span=(3, 4), match='1'> import re s = 'abc1d3e' match_res = re.search('[0-9]',s) if match_res: #先要判斷是否為Noneprint(match_res.group()) #拿到匹配結果 >>> s 'abc1d3e' >>> re.findall('[0-9]',s) #沒有索引 ['1', '3']compile()
re.compile()編譯正則表達式模式,返回一個對象的模式。(可以把那些常用的正則表達式編譯成正則表達式對象,這樣可以提高一點效率。)
格式:re.compile(pattern,flags=0) ?pattern: 編譯時用的表達式字符串。flags 編譯標志位,用于修改正則表達式的匹配方式,如:是否區分大小寫,多行匹配等。
import re tt = "Tina is a good girl, she is cool, clever, and so on..." rr = re.compile(r'\w*oo\w*') print(rr.findall(tt)) #查找所有包含'oo'的單詞 執行結果如下: ['good', 'cool']?
常用的表達式規則
'.' 默認匹配除\n之外的任意一個字符,若指定flag DOTALL,則匹配任意字符,包括換行 '^' 匹配字符開頭,若指定flags MULTILINE,這種也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE) '$' 匹配字符結尾, 若指定flags MULTILINE ,re.search('foo.$','foo1\nfoo2\n',re.MULTILINE).group() 會匹配到foo1 '*' 匹配*號前的字符0次或多次, re.search('a*','aaaabac') 結果'aaaa' '+' 匹配前一個字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 結果['ab', 'abb'] '?' 匹配前一個字符1次或0次 ,re.search('b?','alex').group() 匹配b 0次 '{m}' 匹配前一個字符m次 ,re.search('b{3}','alexbbbs').group() 匹配到'bbb' '{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|45)", "abcabca456c").group() 結果為'abcabca45''\A' 只從字符開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的,相當于re.match('abc',"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'}
?
?'.'匹配除\n以外的任意一個字符(第一個) ? ? ?' ^ ' ?(以.....開頭) ?
>>> s 'abc1d3e' >>> re.search('.',s) <_sre.SRE_Match object; span=(0, 1), match='a'>>>> re.search('.','*abd2') <_sre.SRE_Match object; span=(0, 1), match='*'>>>> re.search('..','*abd2') <_sre.SRE_Match object; span=(0, 2), match='*a'> >>> re.search('^a','abc') <_sre.SRE_Match object; span=(0, 1), match='a'> >>> re.search('^ab','abc') <_sre.SRE_Match object; span=(0, 2), match='ab'> >>> re.match('ab','abc') <_sre.SRE_Match object; span=(0, 2), match='ab'> #它倆相等一樣? ?'$' ?以...結尾;? ‘*’ ?匹配*前的字符0次或多次
>>> re.search('b$','acb') #以b結尾 <_sre.SRE_Match object; span=(2, 3), match='b'>?
>>> re.search('a*','alex').group() #*前邊字符0次或多次 'a' >>> re.search('a*','aaaalex').group() 'aaaa' >>> re.search('ab*','abbaaalex') <_sre.SRE_Match object; span=(0, 3), match='abb'> >>> re.search('ab*','aabbaaalex') <_sre.SRE_Match object; span=(0, 1), match='a'>?'a+'匹配+前一個字符1次或多次;
>>> re.search('a','abbaaalex') <_sre.SRE_Match object; span=(0, 1), match='a'> >>> re.search('a+','abbaaalex') <_sre.SRE_Match object; span=(0, 1), match='a'> >>> re.search('a+','aaab') <_sre.SRE_Match object; span=(0, 3), match='aaa'> >>> re.search('.+','aaabb') <_sre.SRE_Match object; span=(0, 5), match='aaabb'> >>> >>> re.search('ab+','aaabbbb') <_sre.SRE_Match object; span=(2, 7), match='abbbb'>?'?' 匹配前一個字符1次或0次;
>>> re.search('a?','aaabbb') #注意跟*的區別 <_sre.SRE_Match object; span=(0, 1), match='a'> >>> re.search('a?','ddd') <_sre.SRE_Match object; span=(0, 0), match=''>? {m}?匹配前一個字符m次;?{n,m}?匹配前一個字符n到m次;
>>> re.search('a{2}','addad') >>> re.search('a{2}','addaaadt') <_sre.SRE_Match object; span=(3, 5), match='aa'> >>> re.search('.{2}','addaaad') <_sre.SRE_Match object; span=(0, 2), match='ad'> >>> re.search('[0-9]{2}','addaaad234')##必須是連著的兩個數字,隔開的就不行 <_sre.SRE_Match object; span=(7, 9), match='23'>>>> re.search('[a-z]','alex') <_sre.SRE_Match object; span=(0, 1), match='a'> >>> re.search('[a-z]{2}','alex') <_sre.SRE_Match object; span=(0, 2), match='al'> >>> re.search('[a-z]{1,2}','alex') <_sre.SRE_Match object; span=(0, 2), match='al'>>>> re.search('[a-z]{1,2}','a2lex') <_sre.SRE_Match object; span=(0, 1), match='a'> >>> re.search('[a-z]{1,2}','2lex') #{1,2}表示1或者2 <_sre.SRE_Match object; span=(1, 3), match='le'> >>> re.search('[a-z]{1,10}','2lex') <_sre.SRE_Match object; span=(1, 4), match='lex'>? ? ‘|’ ? ?匹配|左或|右的字符
>>> re.search('alex|Alex','Alex') <_sre.SRE_Match object; span=(0, 4), match='Alex'> >>> re.search('a|Alex','alex') <_sre.SRE_Match object; span=(0, 1), match='a'> >>> re.search('[a|A]lex','alex') <_sre.SRE_Match object; span=(0, 4), match='alex'>分組匹配
>>> re.search('[a-z]+[0-9]+' ,'alex123') #alex123,前面必須是以字母開頭,不然就不行了,123alex就不會匹配了 <_sre.SRE_Match object; span=(0, 7), match='alex123'> >>> re.search('[a-z]+[0-9]+' ,'alex123').group() 'alex123'>>> >>> re.search('([a-z]+)([0-9]+)','alex123').groups()#必須是依次對應的,前面要先是字符才能是數字;換成123alex就不匹配了; ('alex', '123') #加s給分開了re.search('^ab','abd') == re.match('ab','abd') == re.search('\Aab','alex')
>>> re.search('\Aalex','alex') <_sre.SRE_Match object; span=(0, 4), match='alex'>?'\A' ? 只從字符開頭匹配;‘\d’ ?匹配數字0-9; ?'\D' ?匹配非數字;
>>> re.search('[0-9]','alex2') <_sre.SRE_Match object; span=(4, 5), match='2'> >>> re.search('\d','alex2') <_sre.SRE_Match object; span=(4, 5), match='2'> >>> re.search('\d+','alexa23456344') <_sre.SRE_Match object; span=(5, 13), match='23456344'> >>> re.search('\d+','alexa23456344f222') <_sre.SRE_Match object; span=(5, 13), match='23456344'>?'\w' ?匹配[A-Za-z0-9] ;‘\W’ ?匹配非[A-Za-z0-9]
>>> re.search('\D+','al^&$exa23456344f222') <_sre.SRE_Match object; span=(0, 8), match='al^&$exa'> >>> >>> >>> re.search('\w+','al^&$exa23456344f222') <_sre.SRE_Match object; span=(0, 2), match='al'> >>> re.search('\w+','alexa23456344f222') <_sre.SRE_Match object; span=(0, 17), match='alexa23456344f222'> >>> re.search('\W+','al^&$exa23456344f222') <_sre.SRE_Match object; span=(2, 5), match='^&$'>?'\s'?匹配空白字符、\t、\n、\r
>>> s = 'alex\njack' >>> s 'alex\njack' >>> print(s) alex jack >>> re.search('\s',s) <_sre.SRE_Match object; span=(4, 5), match='\n'> >>> re.search('\s','slex\njack\tdd\rmack') <_sre.SRE_Match object; span=(4, 5), match='\n'> >>> re.findall('\s','slex\njack\tdd\rmack') ['\n', '\t', '\r'] '(?P<name>...)' 分組匹配 >>> s '130704200005250613' >>> re.search('(?P<province>\d{3})(?P<city>\d{3})(?P<born_city>\d{4})',s).groups () ('130', '704', '2000') >>> res.groupdict() {'province': '130', 'city': '704', 'born_city': '2000'}?split ?
>>> re.split <function split at 0x000000000297C730> >>> s = 'alex22jack23rain31jinxin50' >>> s.split() ['alex22jack23rain31jinxin50'] >>> re.split('\d',s) ['alex', '', 'jack', '', 'rain', '', 'jinxin', '', ''] >>> re.split('\d+',s) ['alex', 'jack', 'rain', 'jinxin', ''] >>> re.findall('\d+',s) ['22', '23', '31', '50']?
>>> s = 'alex22jack23rain31jinxin50#mack-oldboy' >>> re.split('\d+|#|-',s) ['alex', 'jack', 'rain', 'jinxin', '', 'mack', 'oldboy']>>> s = 'alex22jack23rain31jinxin50|mack-oldboy' >>> re.split('\|',s) #加一個\就不把它當做一個語法了,當做一個字符 ['alex22jack23rain31jinxin50', 'mack-oldboy']>>> s = 'alex22jack23rain31\jinxin50|mack-oldboy' >>> s 'alex22jack23rain31\\jinxin50|mack-oldboy'>>> re.split('\\\\',s) #\特殊的轉義字符,特殊匹配 ['alex22jack23rain31', 'jinxin50|mack-oldboy']?
?re.sub()用于替換匹配到的字符串; ? ? re.split() ? ? ?'\d'匹配數字0-9 ? ? ?'+' 匹配字符一次或多次
>>> s 'alex22jack23rain31\\jinxin50|mack-oldboy' >>> re.sub('\d+','_',s) 'alex_jack_rain_\\jinxin_|mack-oldboy' >>> re.sub('\d+','_',s,count=2) #加上count=2是匹配前邊兩個 'alex_jack_rain31\\jinxin50|mack-oldboy'?
>>> s = '9-2*5/3+7/3*99/4*2998+10*568/14' >>> re.split('[-\*/+]',s) ['9', '2', '5', '3', '7', '3', '99', '4', '2998', '10', '568', '14'] >>> re.split('[-\*/+]',s,maxsplit=2) ['9', '2', '5/3+7/3*99/4*2998+10*568/14']?
?
?re.fullmatch()?整個字符串匹配成功就返回re object, 否則返回None
>>> re.fullmatch('alex123','alex123') <_sre.SRE_Match object; span=(0, 7), match='alex123'>>>> re.fullmatch('\w+@\w+\.(com|cn|edu)',"alex@oldboyedu.cn") <_sre.SRE_Match object; span=(0, 17), match='alex@oldboyedu.cn'>標注符Flag
re.I忽略大小寫;
>>> re.search('a','alex') <_sre.SRE_Match object; span=(0, 1), match='a'> >>> re.search('a','Alex',re.I) <_sre.SRE_Match object; span=(0, 1), match='A'>?re.M多行模式,改變'^' '$'的行為
>>> re.search('foo.$','foo1\nfoo2\n') #foo.$ 是以foo結尾后邊任意再匹配一個字符; <_sre.SRE_Match object; span=(5, 9), match='foo2'> >>> re.search('foo.$','foo1\nfoo2\n',re.M) <_sre.SRE_Match object; span=(0, 4), match='foo1'>?re.S 改變‘.’匹配不到\n的行為。
>>> re.search('.','\n',re.S) #.匹配任意的一個字符,可以匹配到\n了 <_sre.SRE_Match object; span=(0, 1), match='\n'>?re.X是可以寫注釋:#注釋
>>> re.search('. #test','alex',re.X) <_sre.SRE_Match object; span=(0, 1), match='a'>?
轉載于:https://www.cnblogs.com/shengyang17/p/9164368.html
總結
以上是生活随笔為你收集整理的第四章: 4.1 logging模块 | 正则表达式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天蚕变哪个厉害
- 下一篇: winScp中文乱码设置