《可愛的Python》讀書筆記(八)
阿新 • • 發佈:2018-03-26
stack chardet 問題的最佳的解決方案,就是找到那段別人解決相似問題的代碼。
今天做些能回顧所學知識點的小練習,類似的問題參考別人的代碼,修改成自己容易理解的模樣。
1、實現簡單的棧。put(item)實現數據item插入棧中;get()實現從棧中取一個數據。
# -*- coding: utf-8 -*- class MyStack(object): '''MyStack 自定義棧,操作有put(), get() ''' def __init__(self): self.head = -1 self.stack = [] def put(self, item): self.head += 1 self.stack.append(item) print('Put %s Success' % item) def get(self): if self.head < 0: return "Put Error: The Stack is Overflow!" else: self.head -= 1 return self.stack.pop() def isEmpty(self): return self.item == [] if __name__ == "__main__": mystack = MyStack() mystack.put('a') mystack.put('b') print(mystack.get()) mystack.put('c') print(mystack.get()) print(mystack.get()) print(mystack.get())
運行結果如下:
Put a Success Put b Success b Put c Success c a Put Error: The Stack is Overflow!
2、判斷指定網頁使用的編碼。
# -*- coding: utf-8 -*- import sys import requests import chardet def web_detect(url): #檢測網頁的編碼方式 try: response = requests.get(url) except: print('error') return 0 web= response.content response.close() codedetect = chardet.detect(web)["encoding"] print('%s\t<-\t%s' % (url, codedetect)) return 1 if __name__ == '__main__': if len(sys.argv) == 1: print('usage:\n\tpython XX.py http://xxx.com') else: web_detect(sys.argv[1])
運行效果如下:
C:\>python webdetect.py http://blog.51cto.com/9473774 http://blog.51cto.com/9473774 <- utf-8 C:\>python webdetect.py http://www.163.com http://www.163.com <- GB2312
3、遍歷指定目錄下的所有文件,找出其中占用空間最大的前3個文件。
# -*- coding: utf-8 -*- import sys import os def get_top_three(path): d = {} for root, dirs, files in os.walk(path): for file in files: fname = os.path.join(root, file) fsize = os.stat(fname).st_size d[fname] = fsize #print(d) f = sorted(zip(d.values(), d.keys())) for i in [-1, -2, -3]: for j in f[i]: print(j) get_top_three('E:\\iso\\CentOS-6.8-x86_64-bin-DVD1')
運行結果如下:
146313216 E:\iso\CentOS-6.8-x86_64-bin-DVD1\images\install.img 45373440 E:\iso\CentOS-6.8-x86_64-bin-DVD1\images\efidisk.img 40688737 E:\iso\CentOS-6.8-x86_64-bin-DVD1\isolinux\initrd.img
《可愛的Python》讀書筆記(八)