學了這些你的python代碼將會改善與你的技巧將會提升。html
比起os模塊的path方法,python3標準庫的pathlib模塊的Path處理起路徑更加的容易。python
前提導入os和pathlib包。。
os版:算法
print(os.path.dirname(__file__)) print(os.getcwd())
pathlib版:編程
print(pathlib.Path.cwd())
看着好像沒啥區別,而後看下面這個。json
os版微信
print(os.path.dirname(os.path.dirname(os.getcwd())))
pathlib版cookie
print(pathlib.Path.cwd().parent.parent)
os版less
print(os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"yamls","a.yaml"))
pathlib版async
parts=["yamls","a.yaml"] print(pathlib.Path.cwd().parent.parent.joinpath(*parts))
os版函數
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'yamls',f'{site_name}.yaml')
pathlib版
parts=["yamls","a.yaml"] print(pathlib.Path(__file__).resolve().parent.parent.joinpath(*parts))
另外pathlib生成的是個對象<class 'pathlib.PosixPath'>,在open文件操做中能夠直接運行的可是若是看成字符串操做會出現錯誤,此時須要對其進行轉換,使用os.fspath()便可,不過通常不多有操做路徑字符串的習慣。
綜合起來,仍是pathlib拼接路徑方便。
編程免不了要寫配置文件,怎麼寫配置也是一門學問。
YAML 是專門用來寫配置文件的語言,很是簡潔和強大,遠比 JSON 格式方便。
YAML在python語言中有PyYAML安裝包。
前提安裝第三方庫
pip install pyaml pip install ruamel.yaml
關於yaml的讀取知識網上一堆了我就不說了,這裏主要說寫入。
from ruamel import yaml data={"age":23,"sex":"男","name":"牛皮"} with open(conf_file, "w", encoding='utf-8') as fs: yaml.dump(data, fs, Dumper=yaml.RoundTripDumper, allow_unicode=True)
yaml寫文件和json同樣也是使用dump。
之前的時候我是這麼解決的
a = ["a", "b", "c", "d"] b = [1, 2, 3] # 空的補充None for index, a_item in enumerate(a): b_item = None if len(b) - 1 <= index: pass else: b_item = b[index] print({a_item:b_item})
如今我經過itertools標準庫的zip升級版zip_longest解決,能夠經過fillvalue參數補充缺失值。固然若是比較的元素個數相同能夠直接用zip。
from itertools import zip_longest a = ["a", "b", "c", "d","e"] b = [1, 2, 3] # 空的補充None for a_item, b_item in zip_longest(a,b,fillvalue=0): print({a_item:b_item})
通常的咱們這樣寫
a="hello" if 2>1 else "bye" print(a)
咱們知道python中false實際式0,true是1,因此對於上面的式子咱們就能夠這麼寫了。
a=["hello","bye"][2<1] print(a)
由於2<1是false也就是0,因此輸出了第一個元素hello。
先來一個簡單的例子
import collections # Person=collections.namedtuple('Person','name age') # 若是使用python中的關鍵字會出現錯誤,此時使用rename字段。 # 按照元素在元組中的下標賦值。class就是_2,def是_3 Person = collections.namedtuple('Person', ['name', 'age', 'class', 'def', 'name', 'name'], rename=True) p = Person(name='lisa', age='12', _2="class2", _3="def", _4="name2", _5="name3") print(p) # 若是出現相同的字段第二次出現的時候也是用其下標,參考上面的例子。 # _fields查看字段名,能夠發現內置模塊和重複的字段標記爲_加下標的形式 print(p._fields) # 使用_asdict將namedtuple轉爲OrderedDict。 od = p._asdict() print(od) # 而後能夠轉爲字典 print(dict(od)) # _replace()方法構建一個新實例,由於namedtuple是不可變類型因此這個方法能夠返回一個新的對象。 new_p = p._replace(name="samJ") print(new_p) print(new_p is p) # 能夠看到不是同一個對象。
一個實用的例子pyppeteer的例子感覺下
import asyncio import pyppeteer from collections import namedtuple Response = namedtuple("rs", "title url html cookies headers history status") async def get_html(url, timeout=30): # 默認30s browser = await pyppeteer.launch(headless=True, args=['--no-sandbox']) page = await browser.newPage() res = await page.goto(url, options={'timeout': int(timeout * 1000)}) data = await page.content() title = await page.title() resp_cookies = await page.cookies() resp_headers = res.headers resp_history = None resp_status = res.status response = Response(title=title, url=url, html=data, cookies=resp_cookies, headers=resp_headers, history=resp_history, status=resp_status) return response if __name__ == '__main__': url_list = ["http://www.10086.cn/index/tj/index_220_220.html", "http://www.10010.com/net5/011/", "http://python.jobbole.com/87541/"] task = (get_html(url) for url in url_list) loop = asyncio.get_event_loop() results = loop.run_until_complete(asyncio.gather(*task)) for res in results: print(res.title)
import enum # 枚舉 @enum.unique class Sex(enum.Enum): man = 12 woman = 13 # 由於加了惟一值的裝飾器因此下面添加屬性會報錯 # boy=12 print(Sex.man.name) print(Sex.woman.value) # 遍歷 for item in Sex: print(item.name) print(item.value) print("-" * 40) # 其餘使用方式 words = enum.Enum( value='item', names=('a b c d e f'), ) # 輸出元素c,必須是上面names裏含有的值 print(words.c) print(words.f) # 由於names不含有w因此報錯 try: print(words.w) except AttributeError as e: print(e.args) print("-" * 40) for word in words: print(word.name, word.value) # 默認賦值爲、從1開始自增。 print("-" * 40) # 若是自定義元素的值嘖改成一下元組的形式 words2 = enum.Enum( value='item2', names=[('a', 23), ('b', 56), ("c", 12), ("d", 333)] ) for word2 in words2: print(word2.name, word2.value)
from collections import ChainMap # ChainMap d1 = {'a': 1, 'b': 2} d2 = {'a2': 3, 'b2': 4} d3 = {'a3': 5, 'b3': 6} d4 = {'a4': 7, 'b4': 8} c = ChainMap(d1, d2, d3, d4) # 多個字典合併爲一個 for k, v in c.items(): print(k, v) print(c.maps) # 要搜索的索引列表 c.maps = list(reversed(c.maps)) # 逆轉映射列表 print(c) # 由於c和d1-d4對應的索引位置實際是一個因此,修改c的時候會影響到d1到d4其中餓的一個值,同理修改 # d1-d4的時候也會影響到c。 # 因此使用new_child建立一個新的映射。再修改就影響不到底層的數據了。 c2 = c.new_child() c2["a4"] = 100 print(c) print(c2) # 輸出發現c的值沒有發生變化,只要c2變化。 d5 = {"a5": 34, "b5": 78} c2 = c2.new_child(d5) # 能夠在原來的映射基礎上添加新的映射 print(c2)
import bisect """ bisect 模塊,用於維護有序列表。 bisect 模塊實現了一個算法用於插入元素到有序列表。 在一些狀況下,這比反覆排序列表或構造一個大的列表再排序的效率更高。 Bisect 是二分法的意思,這裏使用二分法來排序,它會將一個元素插入到一個有序列表的合適位置, 這使得不須要每次調用 sort 的方式維護有序列表。 """ values = [14, 85, 77, 26, 50, 45, 66, 79, 10, 3, 84, 77, 1] print("New Pos Content") print("--- --- -------") l = [] for i in values: postion = bisect.bisect(l, i) # 返回插入的位置 bisect.insort(l, i) # 等於insort_right print('{:3}{:3}'.format(i, postion), l) """ Bisect模塊提供的函數有: bisect.bisect_left(a,x, lo=0, hi=len(a)) : 查找在有序列表 a 中插入 x 的index。lo 和 hi 用於指定列表的區間,默認是使用整個列表。若是 x 已經存在,在其左邊插入。返回值爲 index。 bisect.bisect_right(a,x, lo=0, hi=len(a)) bisect.bisect(a, x,lo=0, hi=len(a)) : 這2個函數和 bisect_left 相似,但若是 x 已經存在,在其右邊插入。 bisect.insort_left(a,x, lo=0, hi=len(a)) : 在有序列表 a 中插入 x。和 a.insert(bisect.bisect_left(a,x, lo, hi), x) 的效果相同。 bisect.insort_right(a,x, lo=0, hi=len(a)) bisect.insort(a, x,lo=0, hi=len(a)) : 和 insort_left 相似,但若是 x 已經存在,在其右邊插入。 Bisect 模塊提供的函數能夠分兩類: bisect* 只用於查找 index, 不進行實際的插入; 而 insort* 則用於實際插入。該模塊比較典型的應用是計算分數等級: """
# 使用&操做符查看字典的相同之處 #字典鍵支持常見的集合操做,並集交集差集。 a = {'x': 1, 'y': 2, 'z': 3} b = {'w': 2, 'z': 4, 'x': 3, 'z': 3} # 獲取相同的鍵 c = a.keys() & b.keys() print(c) # 獲取相同的鍵值對 d = a.items() & b.items() print(d) # 建立一個新的字典並刪除某些鍵 e = {k: a[k] for k in a.keys() - {'z', 'x'}} print(e)
a="safr3.14" print(a[-4:]) #上面能夠改成 pie=slice(len(a)-4,len(a)) print(a)
from collections import Counter text = "abcdfegtehto;grgtgjri" # 可迭代對象 lis = ["a", "c", "d", "t", "b"] dic = {"a": 1, "b": 4, "c": 2, "d": 9} # 字典也能夠 c = Counter() # 能夠定義空容器而後update c.update(text) c2 = Counter() c2.update(dic) c3 = Counter(lis) # 也能夠直接傳入對象 print(c) print(c2) print(c3) # 使用c.most_comman(n)獲取前n出現頻率最高的元素,列表元組類型 print(c.most_common(4))
更多工具使用以及python技巧,請關注公衆號:python學習開發。
若是您喜歡個人文章不防動動小手轉發一波,謝謝。 點擊閱讀原文進入個人博客園,看代碼更方便。 因爲人數超過100因此須要添加我微信:italocxa,而後拉您入羣。