抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

Python 学习

很难绷,编程四五年,现在才学Python

Python是一门很简单的语言,但很多语法跟C++、C#不一样,一眼看上去发现好多不认识的东西,在此记录一下

语法

循环

for i in range(5):
print(i) # 0, 1, 2, 3, 4

循环指定范围

for i in range(1, 5):
print(i) # 1, 2, 3, 4

循环指定步进步长

for i in range(0, 5, 2):
print(i) # 0, 2, 4

索引

Python除了可以使用正向索引,还可以使用负向索引,表示为从最后一个元素开始倒着数,-1是最后一个元素

a = [0, 1, 2, 3, 4, 5]
print(a[0]) # 0
print(a[1]) # 1
print(a[-1]) # 5
print(a[-2]) # 4

这个功能常用于处理路径

file_path = "datasets/xa/xaa/a.json"
file_name = file_path.split('/')[-1] # a.json

异常

try:
if xxx:
raise Exception("There is a error")
except Exception as e:
print(e)

assert

assert <一个bool变量>

若条件为真,程序继续进行

若条件为假,程序抛出AssertionError异常,可以加一个参数信息

assert <一个bool变量>, <一个字符串参数>

容器

切片

Python可以使用切片操作,从一个序列(如列表、元组或字符串)中获取一部分元素

numbers = [0, 1, 2, 3, 4, 5]
print(numbers[:2]) # 输出:[0, 1]
s = "Hello"
print(s[:2]) # 输出:'He'

判断Dict中有无Key

if 'key_name' not in dic:
xxx

列表推导式

List Comprehension

raw = [1, 2, 3, 4, 5]
ans = [x-1 for x in raw] # ans = [0, 1, 2, 3, 4]
import re
input = "<h1><h3><h5><h7>"
pattern = r'<h(\d+)>'
token_lst = [int(match) for match in re.findall(pattern, input)]
# token_lst = [1, 3, 5, 7]

关键词

with

很类似C#的using,用于打开文件,期间代码出现异常会正常关闭,加载的文件也会被关闭释放

with open('file.txt', 'r') as f:
content = f.read()
with open('a.json', 'r') as f:
content = json.loads(f)

sys.argv

传递参数,跟C++ main函数的argv意义相同

# python a1 a2
a1 = sys.argv[1] # a1
a2 = sys.argv[2] # a2

字符串

转为字符串

s = str(o)

格式化数字

在按顺序输出文件名时,经常有格式化数字的需求

num = 12
formatted_str = f"{num:04d}" # 0012

常用库

自定义文件

从自定义的python文件中import函数

# 当前python的同级目录下有一个utils.py文件,文件中定义了一个load_models函数
from utils import load_models

读压缩包

python可以在不解压文件的情况下读取文件内容

import zipfile
# zip
with 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 tarfile
# tar
with 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 subprocess

script_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 pickle

def 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

# 读字符串为json
data = json.loads(input_text)

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

查看视频帧率

import cv2

# 打开视频文件
video_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 plt

x = [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')
# 显示折线的名字
# plt.legend()
if enable_save:
plt.savefig(f'{file_name}.png', dpi=300)

# 显示图表
plt.show()

其他操作

找到site-packages

from distutils.sysconfig import get_python_lib
print(get_python_lib())

调试

话说我发现一些同事居然在用IPython,感觉惊为天人(来自一个使用IDE人的震惊)

from IPython import embed
embed()

评论