1. 程式人生 > >day021 模組(collections,time,random,os,sys)

day021 模組(collections,time,random,os,sys)

關於模組
import
from xxx import xxx
2. Collections
1. Counter 計數器
2. 棧: 先進後出.
佇列:先進先出
deque:雙向佇列
3. defaultdict 預設值字典
4. namedtuple 命名元祖. struct_time 結構化時間就是命名元祖
5. OrederedDict 有序字典。 按照我們儲存的順序儲存. 和3.6以後的字典一樣的
3. time 時間模組
  1. 獲取系統時間 time.time() 時間戳
  2. 格式化時間 strftime() 時間格式: %Y-%m-%d %H:%M:%S %Y-%m-%d
  3. 結構化時間 time.gmtime() time.localtime()
  strptime() 把格式化時間轉化成結構化時間
  mktime() 把結構化時間轉化成時間戳

4. os和sys
os.sep 檔案路徑分隔符
sys.path python查詢模組的路徑

一  、collections

1.  Counter    計數

lst=["a","a","b","g"]
ret=Counter(lst) #lst中的元素必須為可雜湊,不然會報錯
print(dict(ret)) #可將其轉換成字典的形式 #{'a': 2, 'b': 1, 'g': 1}.
from collections import Counter
# #Counter 計數
s="sdffgds sdggdggdgerhumu34$3*7
" q=Counter(s) for i in q: print(i,q[i]) dic={} for i in s: dic[i]=dic.setdefault(i,0)+1 #用字典value 計數 ,setdefault 存在就不做任何操作 print(dic) # li2=["a","a","b","g"] # ret=Counter(li2) # print(ret) lst=["a","a","b","g"] ret=Counter(lst) #lst中的元素必須為可雜湊,不然會報錯 print(dict(ret)) #可將其轉換成字典的形式 #{'a': 2, 'b': 1, 'g': 1}
Counter

2.defaultdict 預設值字典

from collections import defaultdict
# lst=[11,32,22,45,66,77,78]
# d=defaultdict(list)  #d=defaultdict(可呼叫的物件或可執行物件)
# for el in lst:
#     if el>66:
#         d["key1"].append(el) #如果key1不存在時,就會去執行list(),所以d["key1"]=[]
#     else:
#         d["key2"].append(el)
# print(d)  #defaultdict(<class 'list'>, {'key2': [11, 32, 22, 45, 66], 'key1': [77, 78]})
# print(dict(d))  #將其變成字典

def func():
    return "胡辣湯"

d=defaultdict(func)
print(d["a"]) # 胡辣湯 相當d["a"]=func()
print(d["b"]) # 胡辣湯 相當d["a"]=func()
print(dict(d))  #{'a': '胡辣湯', 'b': '胡辣湯'}
defaultdict

3.佇列 queue

#佇列
import queue
#
q = queue.Queue() # 建立佇列
q.put("李嘉誠")
q.put("陳冠希")
q.put("周潤發")
q.put("吳彥祖")

print(q.get())
print(q.get())
print(q.get())
print(q.get())
# print(q.get()) # 佇列中如果沒有元素了. 繼續獲取的話. 會阻塞
print("拿完了")

4.雙向佇列

from collections import deque

q = deque() # 建立一個雙向佇列
q.append("高圓圓")
q.append("江疏影")
q.appendleft("趙又廷")
q.appendleft("劉大哥")
#  劉大哥 趙又廷 高圓圓 江疏影
print(q.pop()) # 從右邊獲取資料
print(q.pop())
print(q.popleft()) # 從左邊獲取資料
print(q.popleft())
print(q.pop())

5.命名元組namedtuple

from collections import namedtuple
# point=namedtuple("Point",["x","y"])    #命名元組  相對於寫了一個類    可用於  寫選單
# p=point(2,5)
# print(p.x)
# print(p.y)

person=namedtuple("Person","name age")
# p=person(name="deng",age=12)
p=person("deng",123)
print(p.name)
print(p.age)

6.orderdict

from collections import OrderedDict
# 按照我們儲存的順序儲存資料
od = OrderedDict({ 'b':'薯條','a':'娃哈哈', 'c':'胡辣湯'})
print(od)

dic = {}
# print(dic["周潤發"]) # 報錯
print(dic.get("周潤發", "英雄本色")) # None

二.time模組

1.獲取當前系統時間, 時間戳   t=time.time()

2.  獲取格式化時間   t= time.strftime("%Y-%m-%d %H:%M:%S") 

3.獲取結構化時間   t = time.localtime()

格式化時間 -> 時間戳

import time
#獲取系統時間  時間戳  time.time()
print(time.time())
#格式化時間  strftime  string   format time   time.strftime(格式)
t=time.strftime("%Y-%m-%d %H:%M:%S")
print(t)
# count=0
# while 1:
#     t2=time.strftime("%S")
#     time.sleep(1)
#     count+=1
#     print(t2)

#結構化時間  time.localtime()
t=time.localtime(1888888000)  #時間戳---》轉化成結構化時間
t2=time.gmtime(0) #格林尼治時間
print(t2)
print(t)#tm_year=2029, tm_mon=11, tm_mday=9, tm_hour=11, tm_min=6, tm_sec=40, tm_wday=4, tm_yday=313, tm_isdst=0
print(t.tm_year)
print(t.tm_mon)
print(t.tm_mday)
print(t.tm_min)
print(t.tm_sec)
print(t.tm_wday)
print(t.tm_yday)

str_time=time.strftime("%Y-%m-%d %H:%M:%S",t)  #將結構化時間轉化成格式化時間,此處的t必須為結構化時間
print(str_time)

#格式化時間轉化成結構化時間     strptime  string parse time      time.strptime(格式化時間,格式化的方式)
s="2018-12-11 8:30:43"
tt=time.strptime(s,"%Y-%m-%d %H:%M:%S")
print(tt)
# #結構化時間轉化成時間戳     time.mktime(結構化時間)
ss=time.mktime(tt)
print(ss)
time模組
import time
#小時 分鐘
t1="2018-10-11 11:12:33"
t2="2020-12-19 8:12:34"
#格式化時間--》結構化時間
struct_time1=time.strptime(t1,"%Y-%m-%d %H:%M:%S")
# print(struct_time1)
struct_time2=time.strptime(t2,"%Y-%m-%d %H:%M:%S")
#結構化時間---》時間戳
t11=time.mktime(struct_time1)
# print(t11)
t12=time.mktime(struct_time2)

# 時間差:
t=t12-t11  #  60  60
# print(t)
h=t//(60*60)
m=(t-h*3600)//60
s=t%60
print(h)
print(m)
print(s)
print("t2和t1的時間差為:%s小時,%s分,%s秒"%(h,m,s))


def time_than(t1,t2):
    '''
    計算時間差的函式
    :param t1: 為格式化時間點1  "%Y-%m-%d %H:%M:%S"
    :param t2:  為格式化時間點2  "%Y-%m-%d %H:%M:%S"
    :return:  以字典形式返回時間差
    '''
    #格式化時間-->結構化時間
    struct_time1 = time.strptime(t1, "%Y-%m-%d %H:%M:%S")
    struct_time2 = time.strptime(t2, "%Y-%m-%d %H:%M:%S")
    #結構化時間--->時間戳
    t11 = time.mktime(struct_time1)
    t12 = time.mktime(struct_time2)
    t=t12-t11
    day=t//(3600*24)
    h=(t-day*3600*24)//3600
    min=(t-day*3600*24-3600*h)//60
    s = t % 60
    return {"day":day,"h":h,"m":m,"s":s}
print(time_than(t1,t2))
時間差
import time
begin = "2019-11-14 16:30:00"
end = "2018-11-14 18:00:00"
# 用時間戳計算出時間差(秒)
begin_struct_time = time.strptime(begin, "%Y-%m-%d %H:%M:%S")
end_stract_time = time.strptime(end, "%Y-%m-%d %H:%M:%S")

begin_second = time.mktime(begin_struct_time)
end_second = time.mktime(end_stract_time)

# 秒級的時間差  180000
diff_time_sec = abs(begin_second - end_second)

# 轉化成結構化時間
t = time.gmtime(diff_time_sec) # 最好用格林尼治時間。 否則有時差
print(t)

print("時間差是%s年%s月 %s天 %s小時%s分鐘" % (t.tm_year-1970, t.tm_mon-1, t.tm_mday-1,t.tm_hour, t.tm_min ))
時間差二

三. random模組

import random
print(random.random())  #產生0-1的隨機小數
print(random.randint(1,9)) #產生一個   1-9 包括1和9 的整數
print(random.randrange(1,9)) ##產生一個   1-9 不包括1和9 的整數
print(random.randrange(1,9,2)) #產生1個  [1,3,5,7]

lst=["a","b",[1,2,"a"],"g"]
print(random.choice(lst))  #從列表lst中隨機取一個元素
print(random.sample(lst,2)) #從列表lst中隨機取2個元素
random.shuffle(lst)    #打亂順序
print(lst)

四  OS模組

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.system("bash command")  運⾏shell命令,直接顯示

os.popen("bash command").read()  運行shell命令,獲取執⾏行行結果

os.getcwd() 獲取當前工作目錄,即當前python指令碼工作的目錄路徑

os.chdir("dirname")  改變當前指令碼工作目錄;相當於shell下cd

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所指向的檔案或者目錄的最後修改時間

os.path.getsize(path) 返回path的大小

#特殊屬性: os.sep    輸出作業系統特定的路徑分隔符,win下為"\\",Linux下為"/"

os.linesep    輸出當前平臺使用的行終止符,win下為"\r\n",Linux下為"\n"

os.pathsep    輸出⽤用於分割檔案路徑的字元串 win下為;, Linux下為:

os.name    輸出字串串指示當前使⽤用平臺。win->'nt'; Linux->'posix' 

五.SYS 模組

所有和python直譯器相關的都在sys模組.  sys.argv 

命令行引數List,第⼀一個元素是程式本身路路徑 sys.exit(n)       

退出程式,正常  退出時   exit(0),          錯誤   退出sys.exit(1)

sys.version        獲取Python解釋程式的版本資訊

sys.path           返回模組的搜尋路徑,初始化時使⽤用PYTHONPATH環境變數量的值

sys.platform       返回作業系統平臺名稱