Python 模块(二)
生活随笔
收集整理的這篇文章主要介紹了
Python 模块(二)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
1 logging 模塊
logging有兩種的配置的方式,configure、logger
1.1 config方式
import logging ''' 日志的配置:config模式 只能選擇在屏幕或者在文件輸出 ''' logging.basicConfig(level=logging.DEBUG,format='%(asctime)s [%(lineno)s] %(message)s' ,filename='log.txt',filemode='a') # logging.debug('debug message') 只有這些內容的時候是只顯示在屏幕 # logging.info('info message') # logging.warning('warning message') # logging.error('error message') # logging.critical('critical message') logging.info('info message')通過logging.basicConig可以配置輸出的格式,level=DEBUG,還可以是INFO、WARNING、ERROR、DIGITAL,這個的優先級是從上往下的。設置好了哪一個就會顯示他后面的。
1.2 logger
推薦用logger
默認的情況是輸出到屏幕的
import logging logger=logging.getLogger()logger.debug('debug message') logger.info('info message') logger.warning('warning message') logger.error('error message') logger.critical('critical message')可通過
import logginglogger=logging.getLogger() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')fh=logging.FileHandler('test.txt') # 文件流 sh=logging.StreamHandler() # 屏幕流fh.setFormatter(formatter) # 這是通過對象實現的設置格式 sh.setFormatter(formatter) #logger.addHandler(fh) logger.addHandler(sh)logger.debug(' logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message')函數的方法:
def logger():logger = logging.getLogger() # 吸星大法fh = logging.FileHandler('logger.txt') # 文件流sh = logging.StreamHandler() # 屏幕流logger.addHandler(fh) # 追加寫 設置成文件寫入logger.addHandler(sh) # 默認是屏幕流 關閉后就屏幕不輸出logger.setLevel(logging.DEBUG) # 設置等級 操作的對象是loggerfm = logging.Formatter('%(asctime)s [%(lineno)s] %(message)s')fh.setFormatter(fm) # 文件的對象# sh.setFormatter(fm) # 屏幕的對象 添加格式return loggerlogger1=logger() # 現在是把函數的運行結果給一個對象# 對象能夠使用方法 logger1.debug('debug message') logger1.info('info message') logger1.warning('warning message') logger1.error('error message') logger1.critical('critical message')2 序列化模塊
2.1 JSON
json是不同語言之間的數據準換
序列化 反序列化
import json ''' 序列化 ''' d={'a':123,"b":456} # 數據格式是字典 s=json.dumps(d) # 轉換成json字符串(實際是Unicode) print(s) # 這是json中的數據 {"a": 123, "b": 456} 是雙引號 print(type(s))# f=open('b.txt','w') # f.write(s) # f.close()''' 反序列化 ''' f=open('b.txt') data=f.read() print(data)data2=json.loads(data) # 現在就是字典的格式 print(data2) json.dump(d,f) # d 是字典 f是文件句柄 有寫入的操作json 應用
import json i=10 s='hello' t=(1,4,6) l=[3,5,7] d={'name':"aa"}json_str1=json.dumps(i) json_str2=json.dumps(s) json_str3=json.dumps(t) json_str4=json.dumps(l) json_str5=json.dumps(d)print(json_str1) #'10' print(json_str2) #'"hello"' print(json_str3) #'[1, 4, 6]' # 元組轉換成json格式 print(json_str4) #'[3, 5, 7]' print(json_str5) #'{"name": "aa"}'2.2 pickle模塊
在python中能夠序列化任何數據類型,是Python專用 的
序列化
import pickle # pickle 是Python文件中間轉換的 import datetime# print(datetime.datetime.now()) t=datetime.datetime.now() d={'data':t}s=pickle.dump(d,open('new','wb')) # json 不支持時間的格式print(s)反序列化
f=open('new','rb') data=pickle.loads(f.read()) print(data)3 正則模塊re
正則是對字符串的模糊匹配
re.findall(‘元字符’,”字符串”)
是字符串中的每一個去對應元字符中的規則
元字符
1.通配符"." # 不能配換行符\n,如果有換行符,返回一個空列表 2.模糊匹配"*" [0,+∞] 3. + [1,+∞] 4. ? [0,1] 5. {} {0,}==* {1,}==+ {0,1}==? 6.字符集 [ab] a b 是或者的關系\* + 是普通字符\- ^ \ 有特殊用處 [0-9]+[a-z]+[^2] 取反[^\d ] 單個[^\d]+ 多個連續的 7.分組() "(ab)+","add" # 分組中默認只有一個 取消優先級(?:) 8. | :或 9. \ \d \w\. \d 匹配任何十進制數;它相當于類 [0-9]。 \D 匹配任何非數字字符;它相當于類 [^0-9]。 \s 匹配任何空白字符;它相當于類 [ \t\n\r\f\v]。 \S 匹配任何非空白字符;它相當于類 [^ \t\n\r\f\v]。 \w 匹配任何字母數字字符;它相當于類 [a-zA-Z0-9_]。 \W 匹配任何非字母數字字符;它相當于類 [^a-zA-Z0-9_] \b 匹配一個特殊字符邊界,比如空格 ,&,#等r'\b','' \b在ASCII中有專門的意思命名分組
res=re.search(r"(?P<A>\w+)\\article\\(?P<id>\d+)", r"abc\article\123", flags=0) print(res) print(res.group("A")) print(res.group("id"))結果:
abc
123
無命名分組
res=re.findall("(ad)+abc", "adabcnnf", flags=0) res=re.findall("(?:ad)+abc", "adabcnnf", flags=0) # 取消優先級結果:
[‘ad’]
[‘adabc’]
finditer 方法
res=re.finditer("\d+", "ad324daa", flags=0) print(res)結果:是一個生成器
callable_iterator object at 0x0000000002B29240>
用next方法
search 方法
search 值匹配第一個結果
res= re.search("\d+", "sjasdff454asef2352", flags=0) print(res) print(res.group())match 方法
mach只在字符串開始的位置匹配
res = re.match("\d+", "123nljklkl2565+6", flags=0) print(res) print(res.group())split 方法
maxsplit是最大的分割次數,默認是0
res=re.split("\d+", "asd123fk234as123df1231sdf132fff", maxsplit=4, flags=0) print(res)[‘asd’, ‘fk’, ‘as’, ‘df’, ‘sdf132fff’] 第5次沒有繼續分割
sub 方法
res = re.sub("\d+", "A","abc2342abc123aaa123", count=3,flags=0) print(res)結果:
abcAabcAaaaA
compile 方法
res = re.compile("\d+", flags=0) res2 = res.findall("hello1232") # 把編譯好的直接用 print(res2)?
轉載于:https://www.cnblogs.com/Python666/p/6785490.html
總結
以上是生活随笔為你收集整理的Python 模块(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#AE创建FeatureDataset
- 下一篇: python基础之名称空间和作用域、函数