Python 学习
很难绷,编程四五年,现在才学Python
Python是一门很简单的语言,但很多语法跟C++、C#不一样,一眼看上去发现好多不认识的东西,在此记录一下
语法
循环
for i in range (5 ): print (i)
循环指定范围
for i in range (1 , 5 ): print (i)
循环指定步进步长
for i in range (0 , 5 , 2 ): print (i)
索引
Python除了可以使用正向索引,还可以使用负向索引,表示为从最后一个元素开始倒着数,-1是最后一个元素
a = [0 , 1 , 2 , 3 , 4 , 5 ] print (a[0 ]) print (a[1 ]) print (a[-1 ]) print (a[-2 ])
这个功能常用于处理路径
file_path = "datasets/xa/xaa/a.json" file_name = file_path.split('/' )[-1 ]
异常
try : if xxx: raise Exception("There is a error" ) except Exception as e: print (e)
assert
若条件为真,程序继续进行
若条件为假,程序抛出AssertionError异常,可以加一个参数信息
assert <一个bool 变量>, <一个字符串参数>
面向对象
创建一个类
class Student : def __init__ (self, student_name ): self.name = student_name def test (self ): print (self.name)
容器
切片
Python可以使用切片操作,从一个序列(如列表、元组或字符串)中获取一部分元素
numbers = [0 , 1 , 2 , 3 , 4 , 5 ] print (numbers[:2 ]) s = "Hello" print (s[:2 ])
判断Dict中有无Key
if 'key_name' not in dic: xxx
列表推导式
List Comprehension
raw = [1 , 2 , 3 , 4 , 5 ] ans = [x-1 for x in raw]
import reinput = "<h1><h3><h5><h7>" pattern = r'<h(\d+)>' token_lst = [int (match ) for match in re.findall(pattern, input )]
关键词
with
很类似C#的using,用于打开文件,期间代码出现异常会正常关闭,加载的文件也会被关闭释放
with open ('file.txt' , 'r' ) as f: content = f.read()
with open ('a.json' , 'r' ) as f: content = json.loads(f)
with open ('a.txt' , 'r' , encoding='utf-8' ) as file: for line in file: print (line.strip())
sys.argv
传递参数,跟C++ main函数的argv意义相同
a1 = sys.argv[1 ] a2 = sys.argv[2 ]
字符串
转为字符串
if s.endswith('.jsonl' ): s.replace('.jsonl' , '.txt' )
格式化数字
在按顺序输出文件名时,经常有格式化数字的需求
num = 12 formatted_str = f"{num:04d} "
常用库
自定义文件
从自定义的python文件中import函数
from utils import load_models
os
遍历目录
访问文件夹下所有文件(递归遍历子文件夹)
for dirpath, dirnames, filenames in os.walk(root_dir): for filename in filenames: file_path = os.path.join(dirpath, filename)
得到文件所在文件夹
不存在就创建文件夹
temp_folder = os.path.dirname(out_path) if not os.path.exists(temp_folder): os.makedirs(temp_folder)
读压缩包
python可以在不解压文件的情况下读取文件内容
import zipfilewith zipfile.ZipFile(f'{file_name} .zip' , 'r' ) as zip_ref: for name in zip_ref.namelist(): print (name) content = zip_ref.read(name).decode('utf-8' )
import tarfilewith tarfile.open (f'uploads/{file_name} .tar' , 'r' ) as tar_ref: for member in tar_ref.getmembers(): print (member.name) content = tar_ref.extractfile(member).read().decode('utf-8' )
发起进程
import subprocessscript_path = 'inference.py' arguments = ['-s' , 'assets/examples/source/hal.jpeg' , '-d' , 'assets/temp/sun.mp4' , '--flag_normalize_lip' ] subprocess.call(['python' , script_path] + arguments)
pkl
将参数存储为二进制
import pickledef read_pkl_file (file_path ): with open (file_path, 'rb' ) as file: data = pickle.load(file) return data def write_pkl_file (file_path, data ): with open (file_path, 'wb' ) as file: pickle.dump(data, file)
随机数
ans = random.uniform(c_min, c_max)
json
data = json.loads(input_text) json_str = json.dumps(data)
moviepy
moviepy是一个处理视频和音频的库
为视频配音
video = mp.VideoFileClip("1.mp4" ) audio = mp.AudioFileClip("2.mp3" ) video = video.set_audio(audio) video.write_videofile("3.mp4" , codec="libx264" , audio_codec="aac" )
opencv
查看视频帧率
pip install opencv-python
import cv2video_path = 's18.mp4' cap = cv2.VideoCapture(video_path) fps = cap.get(cv2.CAP_PROP_FPS) print (f'视频的帧率为:{fps} FPS' )cap.release()
plt
一个画折线图的工具
import matplotlib.pyplot as pltx = [1 , 2 , 3 , 4 , 5 ] y = [2 , 3 , 5 , 7 , 11 ] plt.plot(x, y, marker='o' , linestyle='-' , label='line' ) plt.title('Graph' ) plt.xlabel('Frame' ) plt.ylabel('Value' ) if enable_save: plt.savefig(f'{file_name} .png' , dpi=300 ) plt.show()
ffmpeg
import subprocessdef m4s_to_mp3 (input_file, output_file ): ffmpeg_command = [ "ffmpeg" , "-i" , input_file, "-acodec" , "libmp3lame" , "-q:a" , "2" , output_file ] subprocess.run(ffmpeg_command, check=True ) m4s_to_mp3('a.m4s' , 'a.mp3' )
其他操作
找到site-packages
from distutils.sysconfig import get_python_libprint (get_python_lib())
调试
话说我发现一些同事居然在用IPython,感觉惊为天人(来自一个使用IDE人的震惊)
from IPython import embed embed()