Python 小结
字符串操作
模板字符串
print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")
列表转字符串
'\n'.join(list)
列表合并
def merge_meta(gen_meta, user_meta):
return {**gen_meta, **user_meta}
字符串包含
'substring' in any_string
或者
start = 0
stop = len(any_string)
any_string.find('substring', start, stop)
遍历各行
for line in textData.splitlines():
字符串 /int 互转
int(str)
str(int)
规则表达式
import re
匹配
matches = re.finditer(regex, content, re.MULTILINE)
for match in matches:
meta = match.group(0)
type_name = match.group(1)
type_body = match.group(2)
替换
re.sub(r'(\r\n.?)+', r'\r\n', original)
匹配回调
def _escape_singleline(m):
return "$%s$" % _escape(m)
s2 = re.sub(r'\$(.\*?)\\$', _escape_singleline, s1)
Yaml 文件操作
import yaml
读取
config = yaml.load(open(config_file_path, encoding="utf-8",
mode="r"), Loader=yaml.SafeLoader)
写入
yaml_str = yaml.dump(meta, allow_unicode=True)
字典操作
复制列表
copy.deepcopy(meta)
日期操作
字符串转日期、获取 ISO 日期
parser.parse(new_meta["date"]).astimezone().isoformat()
日期格式化
from datetime import datetime
datetime.today().strftime('%Y-%m-%d_%H%M%S')
其他
判断主模块
if __name__ == "__main__":
生成 slug
def slugify(words):
# https://gist.github.com/hagemann/382adfc57adbd5af078dc93feef01fe1
a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;'
b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------'
p = "|".join(list(a))
# regex = re.compile(p)
slugified_words = words.lower()
maps = [
(r'\s+', '-'),
(r'{}'.format(p), lambda c: b[a.find(c.group(0))]),
(r'&', '-and-'),
(r'[^\w\-]+', ''),
(r'\-\-+', '-'),
(r'^-+', ''),
(r'-+$/', '')
]
for old, new in maps:
slugified_words = re.sub(old, new, slugified_words)
return slugified_words
翻译
def ch_to_en(query):
query = re.sub (r"^ 第 {0,1}(\d+) {0,1} 章", r"ch-\g<1>", query)
url = 'http://fanyi.youdao.com/translate'
data = {
"i": query,
"from": "zh-CHS",
"to": "en",
"smartresult": "dict",
"client": "fanyideskweb",
"salt": "16081210430989",
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"action": "FY_BY_CLICKBUTTION"
}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
+ ' AppleWebKit/537.36 (KHTML, like Gecko) Ch'
+ 'rome/90.0.4430.72 Safari/537.36 Edg/90.0.818.39'
}
response = requests.post(url, data=data, headers=headers)
html = response.content.decode('utf-8')
result = json.loads(html)['translateResult'][0][0]['tgt']
return result
压缩
import zipfile
import os
# Original:
# http://stackoverflow.com/a/6078528
#
# Call `zipit` with the path to either a directory or a file.
# All paths packed into the zip are relative to the directory
# or the directory of the file.
def zip(path, archname):
archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED)
if os.path.isdir(path):
_zippy(path, path, archive)
else:
_, name = os.path.split(path)
archive.write(path, name)
archive.close()
def _zippy(base_path, path, archive):
paths = os.listdir(path)
for p in paths:
p = os.path.join(path, p)
if os.path.isdir(p):
_zippy(base_path, p, archive)
else:
archive.write(p, os.path.relpath(p, base_path))
上传文件
def upload(filename, url, key):
with open(filename, 'rb') as f:
r = requests.post(url,
files={'file': f},
headers={'Authorization': key})
print(r.json())
人性化的数据大小
def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
遍历目录下文件
def get_files(dir_name):
_, _, filenames = next(os.walk(dir_name))
ret = []
for name in filenames:
if not name.endswith(".md"):
continue
ret.append(os.path.join(dir_name, name))
return ret
调用外部命令
from subprocess import call
ret = call("hugo", cwd=get_parent(build_path), shell=True)
获取命令行参数
sys.argv
其中 argv [0]
是当前脚本的名称
路径操作
删除文件夹
import shutil
def clear_dir(dirname):
shutil.rmtree(dirname)
获取父目录
def get_parent(dir = None):
if dir == None:
path = Path(os.getcwd())
else:
path = Path(dir)
return(path.parent.absolute())
获取不带扩展名的文件名
get file name without ext
import os
print(os.path.splitext("/path/to/some/file.txt")[0])