python 小工具方法
onlyforbest
这个作者很懒,什么都没留下…
展开
-
tqdm 设置蓝色进度条,并测试
from tqdm import tqdmfrom colorama import Foreimport timepbar=tqdm(range(1000),bar_format='{l_bar}%s{bar}%s{r_bar}' % (Fore.BLUE, Fore.RESET))for i in pbar : time.sleep(0.001) pbar.set_description("nihao %d"%i)原创 2021-06-07 15:53:58 · 1821 阅读 · 0 评论 -
visdom安装使用(windows)
控制台(cmd)pip install visdom控制台 (启动visdom)python -m visdom.server启动后浏览器输入:可视化默认的是本地服务器 8097端口http://localhost:8097/操作图示测试代码使用:from visdom import Visdomimport timeviz = Visdom()global_step=0for k in range(1000):time.sleep(10...原创 2021-06-07 14:35:02 · 458 阅读 · 1 评论 -
python 处理 json 格式。(数据的存入和读取)
import jsondic={}dic.setdefault(1, [])dic[1].extend([1,2,2])dic.setdefault(2, [])dic[2].extend([1,2,2])print(dic)# 将字典转换成json字符串dict_json=dicwith open("c.json", 'w') as f: f.write(json.dumps(dict_json))# 将json字符串转换成dic字典对象dic = json.load(op.原创 2020-12-30 19:52:21 · 133 阅读 · 0 评论 -
python 字典 与 json 之间的存取对应
import json# 将字典转换成json字符串dict_json={1:5,2:6}with open("a.json", 'w') as f: f.write(json.dumps(dict_json)) # 将json字符串转换成dic字典对象dr_data = json.load(open("a.json"))print(dr_data)原创 2020-12-17 16:15:34 · 141 阅读 · 0 评论 -
Normalize 逐列进行归一化
def Normalize(data): eplision = 1e-7 if data.shape[-1]<=1: _range = np.max(data) - np.min(data) + eplision return (data - np.min(data)) / _range else: for x in range(data.shape[-1]): data[:,x]=(data[:,x] - np.min(data[:,x]) + e.原创 2020-12-07 16:04:58 · 485 阅读 · 0 评论 -
python fire 自动生成 clis
class Calculato(object): """A simple calculator class.""" def doubl(self, number): return 2 * numberif __name__ == '__main__': fire.Fire(Calculato)fire.Fire()生成命令行,clis command line interfaces。将对象或者函数生成命令行的形式。...原创 2020-11-24 15:43:58 · 102 阅读 · 0 评论 -
jupyter 绘图保存图片,并关闭绘图显示,节约内存
import matplotlib.pyplot as pltplt.figure()plt.plot([1,2,3,4,5])plt.savefig("/content/s/fig.jpg")plt.close() #只需要在绘图结尾关闭画笔就好原创 2020-11-17 15:04:36 · 3815 阅读 · 1 评论 -
numpy percentile取分位数+where 表达式
>>> import numpy as np>>> a=np.array([2,3,5,2,34,1])>>> np.percentile(a,80)5.0>>> np.where(a<5)(array([0, 1, 3, 5], dtype=int64),)>>> np.where(a<np.percentile(a,80))(array([0, 1, 3, 5], dtype=int64.原创 2020-11-07 15:38:09 · 5492 阅读 · 0 评论 -
python 指定切分节点对list进行区间切分
import randomls=[random.randint(10,100) for x in range(20)]print(ls)cutindex=[0,2,3,4,5,9,19]for index,cutpoint in enumerate(cutindex[:-1]): if cutindex[0]!=0: temp=ls[:cutindex[index]] if len(temp)!=0: print("ksave",0,cutindex[index]).原创 2020-11-04 20:52:59 · 1064 阅读 · 0 评论 -
plt.tight_layout() 自动调节plt.subplot的间距
plt.figure()plt.subplot(222)plt.title("fig")plt.plot(out[400:600])plt.subplot(221)plt.title("fig")plt.plot(kkout[400:600,1])plt.subplot(224)plt.title("fig")plt.plot(out[1900:2100])plt.subplot(223)plt.title("fig")plt.plot(kkout[1900:2100,1])#.原创 2020-11-01 19:02:59 · 5129 阅读 · 1 评论 -
BLUED 数据集跳过数据表头
import numpy as npdata = np.genfromtxt('location_001_ivdata_002.txt',dtype=str,delimiter=',',skip_header=24)print(data[0])data=np.loadtxt('location_001_ivdata_002.txt',dtype=str,delimiter=',',skiprows=24,)print(data[0])两种方式都是可以的,skip_header和skiprows.原创 2020-10-30 10:20:44 · 1130 阅读 · 7 评论 -
python 判断两整数区间的交并比
def winiou(laba,labb,laca,lacb): axls=[laba,labb,laca,lacb] axlsl=max([laba,laca]) axlsr=min([labb,lacb]) '''右端min-左端max if >0:重叠;else: 0, 下文中的epsilon是为了防止分母为0,python报错''' axls.sort() I=axlsr-axlsl p.原创 2020-10-23 10:14:02 · 526 阅读 · 0 评论 -
python 查找数组中的素数(质数)
def find_prime(nums): result=[] for num in nums: if num > 1: for i in range(2,num): if (num % i) == 0: break else: result.append(num) else: pass return resultfind_prime([3,5,11,12])原创 2020-09-29 09:41:50 · 1914 阅读 · 0 评论 -
python 判断字符串数组是否存在环路
import redef circlejudge(string): if string[0]=='{' and string[-1]=='}': ls=string[1:-1].split(',') print(ls) k=0 for s in ls: pat=re.compile('\([A-Z]->[A-Z]\)') result = re.findall(pat,s) if len(result)!=0: .原创 2020-09-27 19:40:19 · 295 阅读 · 0 评论 -
python 查看文件夹大小
import osdef get_doc_real_size(p_doc): size = 0.0 for root, dirs, files in os.walk(p_doc): size += sum([os.path.getsize(os.path.join(root, file)) for file in files]) size = round(size/1024/1024/1024, 2) return sizeget_doc_real_si.原创 2020-09-27 19:37:47 · 655 阅读 · 0 评论 -
python 将控制台输出记录到文件中
class Logger(object): def __init__(self, filename="Default.log"): self.terminal = sys.stdout self.log = open(filename, "w") def write(self, message): self.terminal.write(message) self.log.write(message) def fl.原创 2020-09-23 20:32:59 · 1038 阅读 · 0 评论 -
python 压缩与解压缩
import zipfileweek=20z = zipfile.ZipFile("/content/sample_data/download_"+str(week)+".zip", 'w', zipfile.ZIP_DEFLATED)startdir = "/content/sample_data/20"os.chdir("/content/sample_data/20")for dirpath, dirnames, filenames in os.walk(startdir): for.原创 2020-09-23 20:30:47 · 113 阅读 · 0 评论 -
python 获取文件大小,正则匹配文件名中的浮点数
1、python 获取os.path.getsize 获取文件大小,StrOfSzize用于 获取选取文件大小单位def StrOfSize(size): ''' 递归实现,精确为最大单位值 + 小数点后三位 ''' def strofsize(integer, remainder, level): if integer >= 1024: remainder = integer % 1024 i..原创 2020-09-17 11:01:43 · 485 阅读 · 0 评论 -
colab or jupyter 添加C 编译环境
!git clone https://github.com/root-project/cling.gitimport osos.chdir("cling/tools/packaging/")!chmod +x cpt.py !./cpt.py --check-requirements && ./cpt.py --create-dev-env Debug --with-workdir=./cling-build/os.chdir("cling/tools/Jupyter.原创 2020-09-09 11:25:50 · 1446 阅读 · 1 评论 -
python 微信推文图片提取,并打包压缩
from re import findallfrom urllib.request import urlopenimport os,shutilimport zipfiledef makedir(path): os.chdir("/") isExists=os.path.exists(path) if isExists: shutil.rmtree(path) else: os.mkdir(path)def getwechatimg(idx,url): pa.原创 2020-08-26 15:01:25 · 383 阅读 · 0 评论 -
python 统计数据区间分布
def distribution(path): '''统计数据分布''' '''载入数据''' relation=np.loadtxt(path, dtype=float, delimiter=" ") total_list=relation '''求取最大值与最小值的差值''' base=math.ceil(max(total_list))-int(min(total_list)) '''设置分布间隔''' coun.原创 2020-08-15 17:59:50 · 4844 阅读 · 0 评论 -
python 绘制多条曲线,曲线颜色随机
import randomdef randomcolor(): colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] color = "" for i in range(6): color += colorArr[random.randint(0,14)] return "#"+colordef huizhi(): xxxx=np.loadtxt("t.原创 2020-08-15 17:47:07 · 5556 阅读 · 2 评论