day21
?個人練習
# coding=utf-8 import re # print(re.findall("a..x","asdfdaesx")) # . 通配符 # print(re.findall('^a..x',"asdfdaesx")) # ^ 只能在字符串的開頭匹配內容 # print(re.findall('^a..x$',"asdfdaesx")) # $ 作為結尾匹配的 # print(re.findall('a..x$',"asdfdaesarrx")) # $ 作為結尾匹配的# 重復符號 * + ? {} # print(re.findall('alex*',"asdfsdfalexxx")) # * 0到無窮次 # print(re.findall('alex*',"asdfsdfale")) # * 0到無窮次 匹配方式:貪婪匹配# print(re.findall('alex+',"asdfsdfalexxx")) # + 1到無窮次 匹配方式:貪婪匹配 # print(re.findall('alex+',"asdfsdfale")) # + 1到無窮次# 把貪婪匹配改成惰性匹配,在后面加? # ret=re.findall('abc*?','abcccccc') # print(ret) # ['ab']# ?匹配【0,1】 # print(re.findall('alex?',"asdfsdfalexxx")) #? 只能匹配0個或者1個 匹配方式:貪婪匹配 # print(re.findall('alex?',"asdfsdfale")) #? 只能匹配0個或者1個# {} 要取多少就取多少 # {0,}==* # {1,}==+ # {0,1}==? # {6} ==6次 # {0,6}==0到6次 # print(re.findall('alex{6}',"asdfsdfalexxx")) # print(re.findall('alex{0,6}',"asdfsdfalexxx")) # print(re.findall('alex{0,1}',"asdfsdfalexxx"))# 元字符之字符集[]:沒有特殊符號 # print(re.findall('x[yz]','xyuuuuxzuu')) # print(re.findall('x[yz]p','xypuuuuxzpuu')) # print(re.findall('x[y,z]p','xypuuuuxzpux,pu')) # print(re.findall('q[a*z]','sdfsqaa')) # print(re.findall('q[a*z]','sdfsq*')) # print(re.findall('q[a-z]','quos')) # 只是取a到z其中的一個 # print(re.findall('q[a-z]*','quos')) # 字符集重復 # print(re.findall('q[a-z]*','quossdfsdf9')) # 9不符合a到z的條件,所以不會出現 # print(re.findall('q[0-9]*','quossdfsdf9')) # print(re.findall('q[0-9]*','q888uossdfsdf9')) # print(re.findall('q[0-9]*','q888uossdfsdfq9')) # print(re.findall('q[A-Z]*','q888uossdfsdfq9')) # print(re.findall('q[^a-z]','q888uossdfsdfq9')) # 匹配不是a到z的 ‘非’ # #在字符集里有功能的符號: - ^ \,其他的都是正常的符號 # print(eval("12+(34*6+2-5*(2-1))")) # print(re.findall("\([^()]*\)","12+(34*6+2-5*(2-1))")) # \d 匹配任何十進制數;它相當于類 [0-9]。 # print(re.findall('\d','12+(34*6+2-5*(2-1))')) # print(re.findall('\d+','12+(34*6+2-5*(2-1))')) # \D 匹配任何非數字字符;它相當于類 [^0-9]。 # print(re.findall('\D+','12+(34*6+2-5*(2-1))')) # \s 匹配任何空白字符;它相當于類 [ \t\n\r\f\v]。 # print(re.findall('\s+','hello world')) # print(re.findall('\S+','hello world')) # print(re.findall('\w','hello world')) # print(re.findall('\W','hello world')) # print(re.findall('www.baidu','www.baidu')) # print(re.findall('www\.baidu','www/baidu')) # print(re.findall('www\.baidu','www.baidu')) # print(re.findall('www*baidu','www*baidu')) # print(re.findall('www\*baidu','www*baidu')) re模塊練習模塊(modue)的概念:
在計算機程序的開發過程中,隨著程序代碼越寫越多,在一個文件里代碼就會越來越長,越來越不容易維護。
為了編寫可維護的代碼,我們把很多函數分組,分別放到不同的文件里,這樣,每個文件包含的代碼就相對較少,很多編程語言都采用這種組織代碼的方式。在Python中,一個.py文件就稱之為一個模塊(Module)。
使用模塊有什么好處?
最大的好處是大大提高了代碼的可維護性。
其次,編寫代碼不必從零開始。當一個模塊編寫完畢,就可以被其他地方引用。我們在編寫程序的時候,也經常引用其他模塊,包括Python內置的模塊和來自第三方的模塊。
所以,模塊一共三種:
- python標準庫
- 第三方模塊
- 應用程序自定義模塊
另外,使用模塊還可以避免函數名和變量名沖突。相同名字的函數和變量完全可以分別存在不同的模塊中,因此,我們自己在編寫模塊時,不必考慮名字會與其他模塊沖突。但是也要注意,盡量不要與內置函數名字沖突
time模塊(* * * *)
三種時間表示
在Python中,通常有這幾種方式來表示時間:
- 時間戳(timestamp) : ? ? ? ??通常來說,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。我們運行“type(time.time())”,返回的是float類型。
- 格式化的時間字符串
- 元組(struct_time) ? : ? ? ? ??struct_time元組共有9個元素共九個元素:(年,月,日,時,分,秒,一年中第幾周,一年中第幾天,夏令時)
time時間模塊
import time # 時間戳 # print(time.time()) #1970年到現在有多少秒,做計算使用 # 結構化時間 # a = time.localtime() # print(a) # print(a.tm_year) # print(a.tm_wday) #從零開始數,表示周幾 # print(time.gmtime()) #世界標椎時間 # print(time.localtime(1236543321)) # 把時間戳轉化成了結構化時間 # 將結構化時間轉化成時間戳 # print(time.mktime(time.localtime())) # 將結構化時間轉換成字符串時間 # print(time.strftime('%Y-%m-%d %X' ,time.localtime())) # X表示時分秒 # 將字符串時間轉化成結構化時間 # print(time.strptime('2019:6:18:7:38:24','%Y:%m:%d:%X')) print(time.asctime()) # 將一個結構化時間轉換成一個固定的字符串時間 print(time.ctime()) # 將一個時間戳轉換成一個固定的字符串時間更直觀import datetime print(datetime.datetime.now()) ?
??? ? ? ? ??
random模塊(* *)
?print(random.random())#(0,1)----float
?print(random.randint(1,3))??#[1,3]
?print(random.randrange(1,3))?#[1,3)
?print(random.choice([1,'23',[4,5]]))#23
?print(random.sample([1,'23',[4,5]],2))#[[4, 5], '23']
?print(random.uniform(1,3))#1.927109612082716
item=[1,3,5,7,9]random.shuffle(item)
print(item)
?
驗證碼 def v_code():ret="" for i in range(5):num = random.randint(0,9)alf = chr(random.randint(65,122))s =str(random.choice([num,alf]))ret+=sreturn ret
?
?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 輸出用于分割文件路徑的字符串 win下為;,Linux下為: 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.maxint???????? 最大的Int值 sys.path?????????? 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 sys.platform?????? 返回操作系統平臺名稱進度條:
import sys,time for i in range(10):sys.stdout.write('#')time.sleep(1)sys.stdout.flush(json & pickle(* * * *)
json(做數據交換使用)
如果我們要在不同的編程語言之間傳遞對象,就必須把對象序列化為標準格式,比如XML,但更好的方法是序列化為JSON,因為JSON表示出來就是一個字符串,可以被所有語言讀取,也可以方便地存儲到磁盤或者通過網絡傳輸。JSON不僅是標準格式,并且比XML更快,而且可以直接在Web頁面中讀取,非常方便。
xml模塊(* *)
xml是實現不同語言或程序之間進行數據交換的協議,跟json差不多,但json使用起來更簡單,不過,古時候,在json還沒誕生的黑暗年代,大家只能選擇用xml呀,至今很多傳統公司如金融行業的很多系統的接口還主要是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>xml數據xml協議在各個語言里的都 是支持的,在python中可以用以下模塊操作xml:
import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml") root = tree.getroot() print(root.tag)#遍歷xml文檔 for child in root:print(child.tag, child.attrib)for i in child:print(i.tag,i.text)#只遍歷year 節點 for node in root.iter('year'):print(node.tag,node.text) #---------------------------------------import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml") root = tree.getroot()#修改 for node in root.iter('year'):new_year = int(node.text) + 1node.text = str(new_year)node.set("updated","yes")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文檔:
import xml.etree.ElementTree as ETnew_xml = ET.Element("namelist") name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"}) age = ET.SubElement(name,"age",attrib={"checked":"no"}) sex = ET.SubElement(name,"sex") sex.text = '33' name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"}) age = ET.SubElement(name2,"age") age.text = '19'et = ET.ElementTree(new_xml) #生成文檔對象 et.write("test.xml", encoding="utf-8",xml_declaration=True)ET.dump(new_xml) #打印生成的格式?re模塊(* * * * *)? ? (day22最后一集)
?就其本質而言,正則表達式(或 RE)是一種小型的、高度專業化的編程語言,(在Python中)它內嵌在Python中,并通過 re 模塊實現。正則表達式模式被編譯成一系列的字節碼,然后由用 C 編寫的匹配引擎執行
字符匹配(普通字符,元字符):
1 普通字符:大多數字符和字母都會和自身匹配
? ? ? ? ? ? ??>>> re.findall('alvin','yuanaleSxalexwupeiqi')
? ? ? ? ? ? ? ? ? ? ? ['alvin']?
2 元字符:. ^ $ * + ? { } [ ] | ( ) \
元字符之. ^ $ * + ? { }
import?re
ret=re.findall('a..in','helloalvin') print(ret)#['alvin'] ret=re.findall('^a...n','alvinhelloawwwn') print(ret)#['alvin'] ret=re.findall('a...n$','alvinhelloawwwn') print(ret)#['awwwn'] ret=re.findall('a...n$','alvinhelloawwwn') print(ret)#['awwwn'] ret=re.findall('abc*','abcccc')#貪婪匹配[0,+oo]?? print(ret)#['abcccc'] ret=re.findall('abc+','abccc')#[1,+oo] print(ret)#['abccc'] ret=re.findall('abc?','abccc')#[0,1] print(ret)#['abc'] ret=re.findall('abc{1,4}','abccc') print(ret)#['abccc'] 貪婪匹配 注意:前面的*,+,?等都是貪婪匹配,也就是盡可能匹配,后面加?號使其變成惰性匹配 ret=re.findall('abc*?','abcccccc') print(ret)#['ab']元字符之字符集[]:
#--------------------------------------------字符集[]
ret=re.findall('a[bc]d','acd') print(ret)#['acd'] ret=re.findall('[a-z]','acd') print(ret)#['a', 'c', 'd'] ret=re.findall('[.*+]','a.cd+') print(ret)#['.', '+'] #在字符集里有功能的符號: - ^ \,其他的符號都是正常符號 ret=re.findall('[1-9]','45dha3') print(ret)#['4', '5', '3'] ret=re.findall('[^ab]','45bdha3') print(ret)#['4', '5', 'd', 'h', '3'] ret=re.findall('[\d]','45bdha3') print(ret)#['4', '5', '3']元字符之轉義符\
反斜杠后邊跟元字符去除特殊功能,比如\.
反斜杠后邊跟普通字符實現特殊功能,比如\d
\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 ?匹配一個特殊字符邊界,比如空格 ,&,#等
ret=re.findall('I\b','I am LIST')
print(ret)#[] ret=re.findall(r'I\b','I am LIST') print(ret)#['I']總結
- 上一篇: day20 函数闭包与装饰器
- 下一篇: day24 面向对象与实例属性