python常用接口调用
文章目录
- 字符串
- 大小写编码/字符判断
- 字典
- 集合
- 列表
- 数组numpy
- 标准输入模板
- 多线程 & 多进程
- pool多线程
- thread多进程
- thread 并行不同的命令
- thread 获取返回值
- json
- 中文读写
- 格式互转
- 时间问题
- pathlib
- matplotlib
- subprocess
- 命令行
- debug小技巧
字符串
- 在字符串中查找匹配的
str.find(str1)
a='dog'
>>> a.find('go') 不存在,局部也不行,返回-1
-1
>>> a.find('og') 存在,但不是从头开始一致,返回1
1
>>> a.find('do') 存在,包含和完全一致,返回0
0
直接对比 if a in b
- 判断字符串内容, 比如是纯数字or纯字母
str.isalnum() 所有字符都是数字或者字母
str.isalpha() 所有字符都是字母
str.isdigit() 所有字符都是数字
str.islower() 所有字符都是小写
str.isupper() 所有字符都是大写
回到目录
- 字符串大小写转换
str = "www.runoob.com"
print(str.upper()) # 把所有字符中的小写字母转换成大写字母
print(str.lower()) # 把所有字符中的大写字母转换成小写字母
print(str.capitalize()) # 把第一个字母转化为大写字母,其余小写
print(str.title()) # 把每个单词的第一个字母转化为大写,其余小写 WWW.RUNOOB.COM
www.runoob.com
Www.runoob.com
Www.Runoob.Com
split和strip的区别
split和strip的区别
大小写编码/字符判断
查看字符编码ord(str)
ord('a')=97 查看字符编码id
小写字符ord编码 : 97-122
大写字符ord编码 : 65-90
if str in range(97,123) 判断单个字符是小写
字典
字典形式
d = {key1 : value1, key2 : value2 }
创建字典
dic={}
赋值操作
dic[key]=value
重复赋相同的值,只出现一次查找操作
If key in dic
返回value, 查value是找不到的按元素放入的先后顺序进行排序
import collectionsdict = collections.OrderedDict()
- 字典中的键映射多个值
参考字典映射多个键值
多个值可能重复
from collections import defaultdictd = defaultdict(list) # list只是属性声明,并不需要替换成真正定过后的list
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
多个值去重后再映射
d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['b'].add(4)
集合
集合形式
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
- 创建集合
a = set()
- 添加元素
a.add('x')
如果已经有的是添加不上的 - 移除某个元素
a.remove('x')
- 查找 `if ‘x’ in a
列表
- 可以当作栈结构使用
list.append(x) 默认加在列表的最后一位
list.pop() 默认弹出的最后一位
list.remove(target) 移除特定的元素
list.reverse() 对列表进行翻转
list.index(obj) 找到对象obj的索引index
list.insert(index, obj) 在对应索引的位置插入对象
list.count(obj) 计算对象obj在index中出现的次数
list.extend(seq) 一次性在列表后添加多个数值, 也可以用 list1+list2 的形式
注意,弹出的时候要判断list是否为空,否则在严格的判断中是会报错的
a=list.pop() if list else '#'
list拼接
a+b
列表和集合相互切换
mailto = ['cc', 'bbbb', 'afa', 'sss', 'bbbb', 'cc', 'shafa']
addr_to = list(set(mailto)) #列表去重
print(addr_to)
addr_to.sort(key=mailto.index) # 按照列表原顺序进行恢复
print(addr_to)
- 判断元素在a中不在列表b中
subtract_list = list(set(a).difference(set(b)))
- list中元素挑选
tar_wav_list = list(filter(lambda x: x.startswith(start_str), wav_list)) ----将wav_list中元素1⃣️‘a'开头的挑选出来组成新的tar_wav_list
数组numpy
- 1维数组反转
a=array([0,1,2]), a[::-1]------[2,1,0]
- 将数组排序
array([[1, 2, 4, 6],[1, 4, 5, 8]])
>>> a=np.array([[4,1,6,2],[5,1,4,8]])
>>> a
array([[4, 1, 6, 2],[5, 1, 4, 8]])
>>> np.sort(a)
array([[1, 2, 4, 6],[1, 4, 5, 8]]) # 直接展示数组从小到大排序后的结果,默认按行排序
>>> np.sort(a, axis=0)
array([[4, 1, 4, 2],[5, 1, 6, 8]]) # 指定维度排序
>>> np.argsort(a)
array([[1, 3, 0, 2],[1, 2, 0, 3]]) ## 将数组a按照从小到大的结果展示index,然后可以选择最大的几维
- 数据四舍五入
>>> int(1.799999)
1
>>> round(1.799999)
2
- 数组中数据选择(条件)
condition = data_array>1
f0_array = np.extract(condition, data_array) --------将数组中数值大于1的挑选出来,组成新的f0_array
- 读入大文件,mmap的方式,让大文件一部分先放在硬盘上,不是完全读取
np.load(input_file, mmap_mode = 'r')
标准输入模板
- 样例1–数字类型
输入第一行包括一个数据组数t(1 <= t <= 100)
接下来每行包括两个正整数a,b(1 <= a, b <= 10^9) ,输出a+b
e.g.输入
#输入
2
1 5
10 20
输出
6
30
import sys
lines = list(sys.stdin)
#对第一行单独处理
t = int(lines[0].strip())
for n in lines[1:]:n = list(n.split(' '))print(int(n[0])+int(n[1]))
或者
#第一行单独处理
t = int(input())
while True:try:line = list(map(int, input().strip().split()))print(line[0]+line[1])except:break
- 样例2–数字类型
输入包括两个正整数a,b(1 <= a, b <= 10^9),输入数据有多组, 如果输入为0 0则结束输入
输入
1 5
10 20
0 0
输出
6
30
while True:try:line = list(map(int, input().strip().split()))# line每次读到的是一行if line[0]==0 & line[1]==0:breakelse:print(line[0]+line[1])except:break
attention
a.split(‘_ ‘) 和a.split()效果一样,a.split(’’)报错
>>> a='a mk ll'
>>> a.split()
['a', 'mk', 'll']
>>> a.split('')
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: empty separator
>>> a.split(' ')
['a', 'mk', 'll']
- 样例3–字符串类型
输入有两行,第一行n, 第二行是n个空格隔开的字符串
输入
5
c d a bb e
输出
a bb c d e
n = int(input())
while True:try:line = list(input().split())line.sort()print(' '.join(line))except:break
attention
想要的输出是序列而不是列表
a=['a', 'b', 'c']
>>> print(a)
['a', 'b', 'c']
>>> print(' '.join(a))
a b c
>>> print(''.join(a))
abc
- 样例4–字符串类型
多个测试用例,每个测试用例一行。每行通过,隔开,有n个字符,n<100
输入
a,c,bb
f,dddd
nowcoder
输出
a,bb,c
dddd,f
nowcoder
while True:try:line = list(input().split(','))line.sort()print(','.join(line))except:break
参考:OJ在线编程常见输入输出练习场 https://ac.nowcoder.com/acm/contest/320#question
多线程 & 多进程
pool多线程
import multiprocessing as mpdef copy_file(name): # 处理单个文件的函数
xxxxpool = mp.Pool(mp.cpu_count()) # 也可以指定线程个数
# pool.map(function, list)
pool.map(copy_file, subtract_list)
子进程和主进程结束时间冲突会报错daemonic processes are not allowed to have children
thread多进程
参考多种方法实现python线程池(threadpool模块\multiprocessing.dummy模块\concurrent.futures模块)
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
import os,time
def task(n):print('%s is runing进程号' %os.getpid())time.sleep(2)return n**2
def main():start_time = time.time()with ThreadPoolExecutor(max_workers=3) as executor:futures = executor.map(task, [i for i in range(10)])print('*'*20)for future in futures:print(future)print('用时共: %s second' % (time.time() - start_time))
if __name__ == '__main__':main()
thread 并行不同的命令
- 正常用法(case1)
import threading, time
def doWaiting(): print('start waiting1: ' + time.strftime('%H:%M:%S') + "\n")time.sleep(3) print('stop waiting1: ' + time.strftime('%H:%M:%S') + "\n")
def doWaiting1(): print('start waiting2: ' + time.strftime('%H:%M:%S') + "\n") time.sleep(8) print('stop waiting2: ', time.strftime('%H:%M:%S') + "\n")thread1 = threading.Thread(target = doWaiting)
thread1.start() thread2 = threading.Thread(target = doWaiting1)
thread2.start() thread1.join() ## 阻塞,所有的进程执行完再推出
thread2.join()
输出的结果:
start waiting1: 14:14:08start waiting2: 14:14:08stop waiting1: 14:14:11stop waiting2: 14:14:16
- case2:join在多个进程间起到阻塞作用
thread1 = threading.Thread(target = doWaiting)
thread1.start()
thread1.join()
t1 = doWaiting() ####主进程
thread2 = threading.Thread(target = doWaiting)
thread2.start()
thread2.join()
执行结果:前一个进程启动join阻塞,下一个进程还没有start,就会等待这个进程结束再开始下一个进程,但是不会阻塞主进程
start waiting1: 14:18:45 //进程1start waiting1: 14:18:45 //主进程stop waiting1: 14:18:48
stop waiting1: 14:18:48start waiting2: 14:18:48 //进程2stop waiting2: 14:18:56
thread 获取返回值
- 通过编写一个类实现
from threading import Thread# _sum = 0def cal_sum(begin, end):# global _sum_sum = 0for i in range(begin, end + 1):_sum += ireturn _sum"""重新定义带返回值的线程类"""class MyThread(Thread):def __init__(self, func, args):super(MyThread, self).__init__()self.func = funcself.args = argsdef run(self):self.result = self.func(*self.args)def get_result(self):try:return self.resultexcept Exception:return Noneif __name__ == '__main__':t1 = MyThread(cal_sum, args=(1, 5))t2 = MyThread(cal_sum, args=(6, 10))t1.start()t2.start()t1.join()t2.join()res1 = t1.get_result()res2 = t2.get_result()print(res1 + res2)
输出55
json
import json
data=[{"startTime":"0.00","endTime":"5.67","content":"来关注境外疫情,澳大利亚维多利亚州州长丹尼尔·安德鲁斯七月六号宣布。 ", "userExtraContent":"女","correct":"正确"},{"startTime":"5 .69","endTime":"11.21","content":"从七号起无限期关闭与新南威尔士州的边界,以防止新冠病毒蔓延。","userExtraContent":"女 ","correct":"正确"},{"startTime":"11.24","endTime":"15.70","content":"维多利亚州近期再次暴发令人担忧的疫情,据路透社报道。","userExtraContent":"女","correct":"正确"}]
读入json格式json.loads(data)
,然后安装列表,读到字典,再根据key读到字典value
中文读写
在读出或写入的时候,加入encoding= 'utf-8'
的注释,中间的dict/set/list都可以正常调用
字典写出和读入
dict={'李明':1, '张三':2}
f = open('test01.txt', 'w', encoding= 'utf-8')
f.write(str(dict))
f.close()f = open('test01.txt', 'r', encoding= 'utf-8')
a = f.read()
dict = eval(a)
print(dict['李明'])
格式互转
- dict转str
str(dict)
- str转dict
eval(str)
- list转str
“ ".join(list)
时间问题
- 以秒计数
import datetime
starttime = datetime.datetime.now()
#long running
#do something other
endtime = datetime.datetime.now()
print (endtime - starttime).seconds
pathlib
- python3中存在pathlib比os.path模块更好用
>>> from pathlib import Path
>>> a='experiments-train/WaveRNN/mel_wavernn'
>>> a=Path(a)
>>> a
PosixPath('experiments-train/WaveRNN/mel_wavernn')
>>> a.parent----相当于os.path.dirname
PosixPath('experiments-train/WaveRNN')
>>> a.parent/'mel' ----------相当于os.path.join()
PosixPath('experiments-train/WaveRNN/mel')
>>> a=Path('experiments-train/WaveRNN/mel_wavernn/01.txt')
>>> a.name------------相当于os.path.basename
'01.txt'filename = Path("source_data/text_files/raw_data.txt")print(filename.name)
# prints "raw_data.txt"print(filename.suffix) -------------文件后缀
# prints "txt"print(filename.stem) ------------文件裸名字
# prints "raw_data"if not filename.exists():print("Oops, file doesn't exist!")
else:
matplotlib
- plot多个子图
- 画柱状图
plt.bar(range(len(num_list)), num_list)
- 设置图片宽高比
time = np.arange(len(src_f0_data))
fig = plt.figure()plt.plot(time, src_f0_data,'r--',label='src_f0')
plt.plot(time, pred_f0_data,'g--',label='pred_f0')plt.xlabel('time')
plt.ylabel('logf0')
plt.legend()
fig.set_size_inches(15, 5) ----在此基础上小幅度调整,更大的速度&加载都会很慢
plt.savefig(fig_path, format='png')
- 设置x轴的刻度 & 调整宽高比
def plot_pitch_phn(pitch_path, phn_path, save_dir):pitch = np.load(pitch_path)pitch = pitch.reshape(-1)phn = open(phn_path, encoding='utf-8-sig').readlines()phn = [i.strip() for i in phn]#print(phn)phn = process_phn_acc_PitchLength(phn)#print('phn:', len(phn), 'pitch', pitch.shape)print(phn)assert len(phn)==len(pitch)fig_name = os.path.basename(pitch_path).split('.')[0] print(fig_name)fig_path = os.path.join(save_dir, '%s.png'%fig_name)x = range(len(pitch))plt.figure(figsize=(20,3)) #放在前边plt.plot(x, pitch, label=fig_name)plt.xticks(x, phn)#plt.rcParams['figure.figsize'] = (5, 1)plt.legend() plt.savefig(fig_path)
subprocess
- 在python内部获取shell命令返回值
cmd = 'xxxx' #shell
result = subprocess.getstatusoutput(cmd)
print(result)
命令行
- 忽视warning的警告信息
python -W ignore xx.py
debug小技巧
- 异常中断
raise ValueError(error information)
- 异常提醒但不中断
try:条件1
except Exception: -----except 异常类型(比如 IOError, Exception--常规错误基类)条件2 --------条件1异常则执行条件2
举个栗子
a=1
try:if a>2:a += 2else: #### 单独的if 条件false并不会进入Exception。要在条件判断中调起;或者直接一个执行条件不合适会启动Exceptionraise Exception
except Exception:print('error: a is ',a)
print失效
为了判断是否进入某一小段命令,有时会使用print debug,但是因为程序执行过程中错误类型不同,可能print的结果并么有打印出来,这时候可以添加print(error information, flush=True)
,会避免print中的内容被冲掉没有输出;
flush
清空缓冲区内容args
print('--------args----------')
for k in list(vars(args).keys()):print('%s: %s' % (k, vars(args)[k]))
print('--------args----------\n')
python常用接口调用相关推荐
- python常用模块-调用系统命令模块(subprocess)
python常用模块-调用系统命令模块(subprocess) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. subproces基本上就是为了取代os.system和os.spaw ...
- 几种常用接口调用方式
个人总结下几种常用的接口调用方式,具体看对方提供的是什么样的webService接口,如有错误,欢迎指正: 1.以前玩微信公众帐号开发的时候,调用过百度翻译的接口,就是这种形式的接口: /** * 翻 ...
- php调用接口搜索的网页源代码,PHP用户管理中常用接口调用实例及解析(含源码)...
掌握用户的第一步就是将已经关注的粉丝信息保存起来,这个时候就用到获取用户列表接口.公众号可通过本接口来获取帐号的关注者列表,关注者列表由一串OpenID(加密后的微信号,每个用户对每个公众号的Open ...
- python api接口调用_python 调用有道api接口的方法
初学者学习python,研究了几天之后,我写了一个python程序调用有道api接口.效果如下图所示:声明:代码仅仅是像我这样的初学者学习和交流.应用程序非常简单.PS:评审不需要时间,请不要滥用!! ...
- php中接口调用方法的区别,phpcms常用接口调用方法
1.phpcms可视化编辑器的调用方法 需要用到editor函数,editor($textareaid = 'content', $toolbar = 'phpcms', $width = 500, ...
- python http接口调用
#http接口解析import requests # 忽略requests证书警告 from requests.packages.urllib3.exceptions import InsecureR ...
- caffe预测、特征可视化python接口调用
转载自: 深度学习(九)caffe预测.特征可视化python接口调用 - hjimce的专栏 - 博客频道 - CSDN.NET http://blog.csdn.net/hjimce/articl ...
- 深度学习(九)caffe预测、特征可视化python接口调用
caffe预测.特征可视化python接口调用 原文地址:http://blog.csdn.net/hjimce/article/details/48972877 作者:hjimce 网上有很多caf ...
- python caffe 训练自己的模型_python接口调用已训练好的caffe模型测试分类方法
训练好了model后,可以通过python调用caffe的模型,然后进行模型测试的输出. 本次测试主要依靠的模型是在caffe模型里面自带训练好的结构参数:~/caffe/models/bvlc_re ...
最新文章
- 从AlexNet到DenseNet,再到SENet,一文看懂图像分类领域的突破性进展
- 生活问题 | 对华为畅玩手机5X进行升级
- JavaScript——易班优课YOOC课群在线测试自动答题解决方案(十五)整合升级+引入jQuery
- SpringMVC-方法四种类型返回值总结,你用过几种?
- src获取同级目录中的图片_一个简单的Python爬虫实例:百度贴吧页面下载图片
- 非maven配置SpringBoot框架
- redis安装与基本配置
- mysql选中一行数据_获取table选中一行数据库
- java版本不兼容_java 中jdk版本不兼容的问题小记
- 见过一些能力非常强的但创业总是失败
- Header First设计模式学习笔记——单例模式
- [转]网店博客营销之微博实战技巧:还没有做微博的掌柜看过来
- EXCEL MATCH函数
- 2022-07-02 Android 进入app 后 距离传感器控制手机屏幕熄灭的方法-接近传感器Proximity Sensor的信号
- 脾气暴躁的 Linus 不大可能开喷修改 master
- Spring Hystrix 原理与使用详解
- Xshell连接服务器
- Linux笔记-ftp主动和被动模式下iptables的规则配置
- 十、不足两位用0补齐
- 3d文本样式cssjs特效代码
热门文章
- c语言中,exit(1)是什么意思?
- 2021-基于深度学习的人脸检测综述文献-摘要
- vscode代码自动格式化快捷键
- 工业poe交换机供电方法
- 收藏!2022年开发运维必备的10款顶级工具
- python -不敢表白,不好意思说出来,没关系,7行代码完成自动打印文字
- 深入探索Linux虚拟化KVM-Qemu分析之CPU虚拟化
- 中国大学MOOC大学生心理健康试题及答案
- 普通话测试软件哪个不要钱,普通话测试软件哪个好_普通话测试软件靠谱吗_不要钱的普通话测试软件...
- svn提交代码报错:A conflict in the working copy obstructs the current operation,解决办法