比起 os 模块的 path 方法,python3 标准库的 pathlib 模块的 Path 处理起路径更加的容易。 ####获取当前文件路径 前提导入 os 和 pathlib 包。。 os 版:php
print(os.path.dirname(__file__)) print(os.getcwd())
pathlib 版:css
print(pathlib.Path.cwd())
看着好像没啥区别,而后看下面这个。html
os 版python
print(os.path.dirname(os.path.dirname(os.getcwd())))
pathlib 版算法
print(pathlib.Path.cwd().parent.parent)
os 版编程
print(os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"yamls","a.yaml"))
pathlib 版json
parts=["yamls","a.yaml"] print(pathlib.Path.cwd().parent.parent.joinpath(*parts))
os 版bash
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'yamls',f'{site_name}.yaml')
pathlib 版markdown
parts=["yamls","a.yaml"] print(pathlib.Path(__file__).resolve().parent.parent.joinpath(*parts))
另外 pathlib 生成的是个对象<class 'pathlib.PosixPath'>,在 open 文件操做中能够直接运行的可是若是看成字符串操做会出现错误,此时须要对其进行转换,使用 os.fspath()便可,不过通常不多有操做路径字符串的习惯。 综合起来,仍是 pathlib 拼接路径方便。cookie
编程免不了要写配置文件,怎么写配置也是一门学问。 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))
import enum # 枚举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)