import math
|
import hashlib
|
import os
|
import json
|
import re
|
|
|
def get_bit_mask(start, end):
|
bits = math.ceil((end + 1) / 8) * 8
|
if bits == 0:
|
bits = 8
|
mask = 0
|
for i in range(start, end + 1):
|
mask |= 1 << (bits - i - 1)
|
return mask
|
|
|
def generate_md5(input_string):
|
# 创建一个 md5 哈希对象
|
md5_hash = hashlib.md5()
|
|
# 更新哈希对象的内容(需要将字符串编码为字节)
|
md5_hash.update(input_string.encode('utf-8'))
|
|
# 获取哈希值的十六进制表示
|
md5_digest = md5_hash.hexdigest()
|
|
return md5_digest
|
|
|
def file_exists(cache_file: str):
|
return os.path.exists(cache_file)
|
|
|
def read_from_file(cache_file: str) -> str:
|
with open(cache_file, 'r', encoding='utf-8') as f:
|
text = f.read()
|
return text
|
|
|
def save_to_file(text, cache_file):
|
with open(cache_file, 'w', encoding='utf-8') as f:
|
f.write(text)
|
|
|
def replace_tpl_paras(tpl_text: str, data: dict):
|
for key, val in data.items():
|
if not isinstance(val, str):
|
val = json.dumps(json.dumps(val, ensure_ascii=False), ensure_ascii=False)[1:-1]
|
tpl_text = tpl_text.replace('{{' + key + '}}', val)
|
return tpl_text
|
|
|
def to_file_name(text: str):
|
"""
|
将文本转为合法的文件名称。
|
将特殊字符替换为_
|
:param text:
|
:return:
|
"""
|
return re.sub(r'[\\/:*?"<>|]', '_', text)
|