python-opencv 日常使用笔记

print

将数据输出到文件中

fp = open('D:text.txt', 'a+') #如果不存在就创建,存在则追加内容
print('hello world',file = fp)
fp.close()

转义字符

\n换行
\t制表位(四个字符为一个制表位)
\r覆盖
\b退一个格
r’ ’原字符,最后一个字符不能是反斜杠

标识符

imort ketword
print(keyword.kwlist)

数据类型

整数类型

int

十进制
二进制0b
八进制0o
十六进制0x

浮点数类型

浮点数计算可能不精确,解决方法:

from decimal import Decimal
print(Decimal('1.1') +Decimal('2.2'))

布尔类型

布尔类型可以参与计算

  • True 1
  • False 0

字符串类型

注意英文引号,三引号可以多行

str = 'python 是世界上最好用的语言'
str = "python 是世界上最好用的语言"
str = """python 是世界上
	最好用的语言"""

类型转换

str()  # 将其他类型转换成str
int()  # 将字符串转为int类型时,必须为整数数字串
float() # 转为浮点型,.0

注释


#coding:utf-8  中文编码声明
# 单行注释
'''
多行注释
'''

input

input 接收的是str类型

a = int(input('请输入一个整数'))

运算符

算术运算符

//整除运算 负数:向下取整
%取余运算
**幂运算

余 数 = 被 除 数 − 除 数 ∗ 商 余数=被除数-除数*商 =

赋值运算符

解包赋值

比较运算符

==  # 比较的值
is is not # 比较的是标识id
print(id(list))

布尔运算符

and两个结果都为true,结果才为true
or一个为true,结果就为true
not取反
in在…中
not in不在…中

位运算符

按位与 & 同为1时结果为1
按位或 |
向左移动 << 高位溢出,低位补0 相当于×2
向右移位 >> 高位补0,低位截断 相当于÷2

运算符优先级

幂运算 乘除 加减
左移右移 与 或
比较运算符
布尔运算符
赋值运算

程序分支结构

if语句

if n%2>==0:
	a = a + 1
else:
	a = a - 1	
score = int(input('请输入一个整数'))
if score >=90 and score <=100:  # 90 <=score<=100
	print('A')
elif score >=80 and score < 90:
	print('B')
else:
	print('none')

条件 表达式

功能:简化代码

print(str(num_a)+'大于等于' +str(num_b) if num_a >=num_b else str(num_a)+'小于' +str(num_b)
pass语句: 占位符,搭建语法结构时使用

内置函数

range

不管range对象的数列有多长,在内存中都是一样的,仅存储起始,结束和步长,只有用到时才会计算相关元素
range(10) #默认从0开始,步长为1
range(1,10)  # [1,10)
range(1,10,1)

循环结构

  1. 初始化变量
  2. 条件判断
  3. 条件执行
  4. 改变变量

计算0~100之间的偶数和

sum = 0
a = 0
while a <=100:
	if a%2 == 0:  # if not bool(a%2)
		sum += a
	a += 1
for _ in range(5):
	print('不需要使用自定义变量')
for i in range(100,1000):
	if i == (i//100) **3 + (i//10 %10) ** 3 + (i%10) **3 :
		print('水仙花')

打印99乘法表:

for i in range(1,10):
	for j in range(1,i+1):
		print(i,'*',j,'=',i*j, end='\t' )  # 想打印制表符用print(xxx,end='\t')
	print('\n')
1 * 1 = 1		

2 * 1 = 2		2 * 2 = 4		

3 * 1 = 3		3 * 2 = 6		3 * 3 = 9		

4 * 1 = 4		4 * 2 = 8		4 * 3 = 12		4 * 4 = 16		

5 * 1 = 5		5 * 2 = 10		5 * 3 = 15		5 * 4 = 20		5 * 5 = 25		

6 * 1 = 6		6 * 2 = 12		6 * 3 = 18		6 * 4 = 24		6 * 5 = 30		6 * 6 = 36		

7 * 1 = 7		7 * 2 = 14		7 * 3 = 21		7 * 4 = 28		7 * 5 = 35		7 * 6 = 42		7 * 7 = 49		

8 * 1 = 8		8 * 2 = 16		8 * 3 = 24		8 * 4 = 32		8 * 5 = 40		8 * 6 = 48		8 * 7 = 56		8 * 8 = 64		

9 * 1 = 9		9 * 2 = 18		9 * 3 = 27		9 * 4 = 36		9 * 5 = 45		9 * 6 = 54		9 * 7 = 63		9 * 8 = 72		9 * 9 = 81		


break语句:跳出循环
continue语句:结束当前循环,直接进入下一次循环
只用于本层循环

没有break执行else,遇到break不执行else

for item in range(3):
	pwd=imput('')
	if pwd=='8888':
		print('ok')
		break
	else:
		print('ohoo')
else:
	print('okkk')
	
以下对象的布尔值为 False 0 0.0 空字符串 空[列表 元组 元组 字典 集合]

图像灰度最大值

# 找出最大灰度值
def maxGrayLevel(img):
    max_gray_level = 0
    (height, width) = img.shape
    # print
    # height, width
    for y in range(height):
        for x in range(width):
            if img[y][x] > max_gray_level:
                max_gray_level = img[y][x]
    return max_gray_level + 1

图像分块

# 图像分块  将图像分为3×3块
def divide_img(img_path, img_name, save_path):
    imgg = img_path + img_name
    img = cv2.imread(imgg)
    #   img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    h = img.shape[0]
    w = img.shape[1]
    n = 3
    m = 3
    print('h={},w={},n={},m={}'.format(h, w, n, m))
    dis_h = int(np.floor(h / n))
    dis_w = int(np.floor(w / m))
    num = 0
    for i in range(n):
        for j in range(m):
            num += 1
            print('i,j={}{}'.format(i, j))
            sub = img[dis_h * i:dis_h * (i + 1), dis_w * j:dis_w * (j + 1), :]
            cv2.imwrite(save_path + '_{}.bmp'.format(num), sub)

 	img = cv.imread(path, 0)
    dst = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
    bg = cv.morphologyEx(dst, cv.MORPH_CLOSE, kernel)
    ob = cv.subtract(img, bg)
# 绘制高斯图
def plotGuass(sigma):
    x = np.linspace(-1,1,100)
    y = np.linspace(-1,1,100)
    X, Y = np.meshgrid(x, y)

    Z = (1/2*math.pi*sigma**2)*np.exp(-(X**2+Y**2)/2*sigma**2)
    ax = plt.subplot(111, projection='3d')
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='jet', alpha=0.9)  # 绘面

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.savefig('test.png')
    plt.show()

在这里插入图片描述

# 图像拼接
def image_stitching(imgs):
    IMAGE_ROW = 6
    IMAGE_COLUMN = 6
    avg_width = 1004
    avg_height = 1004
    index = 0
    new_image = Image.new('RGB', (IMAGE_COLUMN * avg_width, IMAGE_ROW * avg_height))  # 创建一个新图

    # 循环遍历,把每张图片按顺序粘贴到对应位置上
    for i in range(IMAGE_ROW):
        for j in range(IMAGE_COLUMN):
            new_image.paste(imgs[index], (i * avg_height, j * avg_width))  # 将图像粘贴到指定位置
            index += 1

    return new_image
# 遍历文件夹
def iter_files(rootDir, extend_name):
    imgs = []
    # Iterate over the roots
    for root, dirs, files in os.walk(rootDir):
        for file in files:
            root = os.path.normpath(root)  # 格式化路径 斜杠问题
            file_name = os.path.join(root, file)  # 连接路径
            # print(file_name)
            flag = file_name.endswith(extend_name)
            if flag:
                img = Image.open(file_name)
                imgs.append(img)
                # file_list.append(file_name)

#保存图片
 cv2.imwrite(save_path + '{:0>4}{:0>2}.jpg'.format(index, num), sub)  # : 填充符号、对齐方式(> 右对齐,< 左对齐,^ 居中对齐)、宽度、进制

plt.savefig('new_image.jpg',dpi=500,bbox_inches = 'tight')
# 重命名文件
    def rename(self):
        filelist = os.listdir(self.path) #获取文件路径
        total_num = len(filelist) #获取文件长度(个数)
        i = 1  #表示文件的命名是从1开始的
        for item in filelist:
            if item.endswith('.png'):  #初始的图片的格式为jpg格式的(或者源文件是png格式及其他格式,后面的转换格式就可以调整为自己需要的格式即可)
                src = os.path.join(os.path.abspath(self.path), item)
                #dst = os.path.join(os.path.abspath(self.path), ''+str(i) + '.jpg')#处理后的格式也为jpg格式的,当然这里可以改成png格式
                dst = os.path.join(os.path.abspath(self.path), '0' + format(str(i), '0>3s') + '.jpg')      #这种情况下的命名格式为000000.jpg形式,可以自主定义想要的格式
                # dst = os.path.join(os.path.abspath(self.path), str(i) + '.jpg')
                try:
                    os.rename(src, dst)
                    # print ('converting %s to %s ...' % (src, dst))
                    i = i + 1
                except:
                    continue
        print ('total %d to rename & converted %d jpgs' % (total_num, i))
#绘制柱状图
index = np.arange(4)
data1 = np.array([5,5,6,3])
data2 = np.array([6,2,1,5])


a = 0.3
plt.ylabel('False count')

plt.barh(index, data1, a, color = 'pink', hatch = '/', label='FP')
plt.barh(index, data2, a, left = data1,           # 堆叠在左边第一个上方
        color = 'c', label = 'FN')


plt.legend()
plt.axis('off')
plt.savefig('bar.png')
plt.show()

在这里插入图片描述

小波变换

ModuleNotFoundError: No module named 'pywt’
在这里插入图片描述

import numpy as np
import pywt
import cv2
import matplotlib.pyplot as plt

img = cv2.imread("1.png")
img = cv2.resize(img, (448, 448))
# 将多通道图像变为单通道图像
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).astype(np.float32)

plt.figure('二维小波一级变换')
coeffs = pywt.dwt2(img, 'haar')
cA, (cH, cV, cD) = coeffs

plt.subplot(221), plt.imshow(cA, 'gray'), plt.title("A")
plt.subplot(222), plt.imshow(cH, 'gray'), plt.title("H")
plt.subplot(223), plt.imshow(cV, 'gray'), plt.title("V")
plt.subplot(224), plt.imshow(cD, 'gray'), plt.title("D")


plt.figure('二维图像多级分解')
coeffs = pywt.wavedec2(img, 'haar', level=2)
cA2, (cH2, cV2, cD2), (cH1, cV1, cD1) = coeffs

# 将每个子图的像素范围都归一化到与CA2一致  CA2 [0,255* 2**level]
AH2 = np.concatenate([cA2, cH2+510], axis=1)
VD2 = np.concatenate([cV2+510, cD2+510], axis=1)
cA1 = np.concatenate([AH2, VD2], axis=0)

AH = np.concatenate([cA1, (cH1+255)*2], axis=1)
VD = np.concatenate([(cV1+255)*2, (cD1+255)*2], axis=1)
img = np.concatenate([AH, VD], axis=0)

plt.imshow(img,'gray')
plt.title('2D WT')
plt.show()

图像绘制矩形框并去除白边

import cv2 as cv
import matplotlib.pyplot as plt

img = cv.imread('0004.png')

font = cv.FONT_HERSHEY_PLAIN
text = 'prediction'
# cv.putText(img, text, (63, 34), font, 1, (0,0,0), 2)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
rect = plt.Rectangle((63, 34), 150, 104, fill=False, edgecolor = 'red',linewidth=1)
rect1 = plt.Rectangle((75, 36), 121, 120, fill=False, edgecolor = 'blue',linewidth=1)
ax.add_patch(rect)  # sdd_patch 将创建的形状放进去
ax.add_patch(rect1)
# plt.legend()
# cv.imshow('img', img)
plt.imshow(img)
plt.axis('off')

########去除白边####
height, width, channels = img.shape
# 如果dpi=300,那么图像大小=height*width
fig.set_size_inches(width/100.0/3.0, height/100.0/3.0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.subplots_adjust(top=1,bottom=0,left=0,right=1,hspace=0,wspace=0)
plt.margins(0,0)
# plt.style.use('science')
plt.savefig('test1.png', dpi=300)
plt.show()
 plt.ion()  # 将画图模式改为交互模式,程序遇到plt.show不会暂停,而是继续执行

绘制混淆矩阵

#confusion_matrix
import numpy as np
import matplotlib.pyplot as plt
classes = ['A','B','C','D','E']
confusion_matrix = np.array([(9,1,3,4,0),(2,13,1,3,4),(1,4,10,0,13),(3,1,1,17,0),(0,0,0,1,14)],dtype=np.float64)

plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Oranges)  #按照像素显示出矩阵
plt.title('confusion_matrix')
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=-45)
plt.yticks(tick_marks, classes)

thresh = confusion_matrix.max() / 2.
#iters = [[i,j] for i in range(len(classes)) for j in range((classes))]
#ij配对,遍历矩阵迭代器
iters = np.reshape([[[i,j] for j in range(5)] for i in range(5)],(confusion_matrix.size,2))
for i, j in iters:
    plt.text(j, i, format(confusion_matrix[i, j]))   #显示对应的数字

plt.ylabel('Real label')
plt.xlabel('Prediction')
plt.tight_layout()
# plt.style.use('science')
plt.savefig('confudion_matrix.png')
plt.show()


傅里叶变换

# -*- coding: utf-8 -*-
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

#读取图像
img = cv.imread('lena.jpg', 0)
#快速傅里叶变换算法得到频率分布
f = np.fft.fft2(img)
#默认结果中心点位置是在左上角,
#调用fftshift()函数转移到中间位置
fshift = np.fft.fftshift(f)
#fft结果是复数, 其绝对值结果是振幅
fimg = np.log(np.abs(fshift))
#展示结果
plt.subplot(121), plt.imshow(img, 'gray'), plt.title('Original Fourier')
plt.axis('off')
plt.subplot(122), plt.imshow(fimg, 'gray'), plt.title('Fourier Fourier')
plt.axis('off')
plt.savefig('lena1.png', dpi=300)
plt.show()


在这里插入图片描述

模板匹配

import cv2  #opencv读取的格式是BGR
import numpy as np
from matplotlib import pyplot as plt

# 模板匹配
img = cv2.imread('lena.jpg', -1)  # 0 - 单通道读取图像
template = cv2.imread('face.jpg', -1)

h, w = template.shape[:2]
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
           'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']

i = 1
for meth in methods:
    img2 = img.copy()
    # img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 匹配方法的真值
    method = eval(meth)  #将字符串string对象转化为有效的表达式参与求值运算返回计算结果
    print (method)
    res = cv2.matchTemplate(img2, template, method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

    # 如果是平方差匹配TM_SQDIFF或归一化平方差匹配TM_SQDIFF_NORMED,取最小值
    if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)

    


    # 画矩形
    cv2.rectangle(img2, top_left, bottom_right, (255,255,255), 2)

    plt.subplot(121), plt.imshow(res, cmap='gray')
    plt.xticks([]), plt.yticks([])  # 隐藏坐标轴
    plt.subplot(122), plt.imshow(img2, cmap='gray')
    plt.xticks([]), plt.yticks([])

    plt.savefig("%d.jpg" % (i))
    i = i + 1
    plt.show()

    cv2.waitKey(0)

在这里插入图片描述

基本操作

	gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

    # blurred = cv.medianBlur(gray, 5)
    blurred = cv.GaussianBlur(gray, (5, 5), 0)
    cv_show('blurred', blurred)
    edged = cv.Canny(blurred, 10, 90)
    cv_show('edged', edged)
    th = cv.adaptiveThreshold(blurred, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2)
    cv_show('1', th)
    res = np.rint(res).astype('uint8')  # np.rint()是根据四舍五入取整
    
# -*- coding: utf-8 -*-
import numpy as np
import cv2 as cv
import pylab as pl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter

#读取图像
img = cv.imread("11.jpg")


#  if(img.shape[2])
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# img = 255 - img

imgd = np.array(img)      #image类转numpy


#准备数据
sp = img.shape
h = int(sp[0])        #图像高度(rows)
w = int(sp[1])       #图像宽度(colums) of image
#绘图初始处理
fig = plt.figure(1)
ax = fig.gca(projection="3d")
x = np.arange(0, w, 1)
y = np.arange(0, h, 1)
x, y = np.meshgrid(x,y)
z = imgd
surf = ax.plot_surface(x, y, z, cmap=cm.jet)
#自定义z轴
ax.set_zlim(-10, 255)
ax.zaxis.set_major_locator(LinearLocator(10))   #设置z轴网格线的疏密
#将z的value字符串转为float并保留2位小数
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# 设置坐标轴的label和标题
ax.set_xlabel('x', size=15)
ax.set_ylabel('y', size=15)
ax.set_zlabel('z', size=15)
ax.set_title("surface plot", weight='bold', size=20)

#添加右侧的色卡条
fig.colorbar(surf, shrink=0.6, aspect=8)
# 投影
# ax.plot_surface(x, y, z, rstride=8, cstride=8, alpha=0.3)
# cset = ax.contourf(x, y, z, zdir='z', offset=-100, cmap=cm.coolwarm)
# cset = ax.contourf(x, y, z, zdir='x', offset=-40, cmap=cm.coolwarm)
# cset = ax.contourf(x, y, z, zdir='y', offset=40, cmap=cm.coolwarm)

#保存为pdf
#plt.savefig("example.pdf", format = "pdf",  bbox_inches='tight')
plt.savefig("ex.png", dpi = 300)
plt.show()

在这里插入图片描述

最大值、最小值滤波

def maxConv(img, size):
    height, width = img.shape
    # (图像尺寸+padding尺寸-卷积核尺寸)/步长+1
    new_h = height - size + 1
    new_w = width - size + 1
    new_image = np.zeros((new_h, new_w), dtype=np.float)
    for i in range(new_h):  #原作者写反了
        for j in range(new_w):

            new_image[i, j] = np.max(img[i:i + size, j:j + size] )

    new_image = new_image.clip(0, 255)
    # new_image = np.rint(new_image).astype('uint8')
    return new_image

def minConv(img, size):
    height, width = img.shape
    # (图像尺寸+padding尺寸-卷积核尺寸)/步长+1
    new_h = height - size + 1
    new_w = width - size + 1
    new_image = np.zeros((new_h, new_w), dtype=np.float)
    for i in range(new_h):  #原作者写反了
        for j in range(new_w):

            new_image[i, j] = np.min(img[i:i + size, j:j + size] )

    new_image = new_image.clip(0, 255)
    # new_image = np.rint(new_image).astype('uint8')
    return new_image

网络预测

file_list = iter_files('D:\github\centernet\VOCdevkit\VOC2007\JPEGImages' ,'png')
num = 0
for name in file_list:

    image = Image.open(name)
        # 转为彩色图
    image = image.convert('RGB')
    r_image = centernet.detect_image(image)
    num = num + 1
    r_image.save('save_path/%d.bmp'%(num))


     

IEEE科研绘图


import matplotlib.pyplot as plt
plt.style.use(['science','ieee'])


import numpy as np
import matplotlib.pyplot as plt
def model(x, p): 
   return x ** p
x = np.linspace(0, 1, 101)



with plt.style.context(['science', 'ieee']):
    fig, ax = plt.subplots()    
for p in [0.2, 0.67, 1, 2.5, 10]:       
        ax.plot(x, model(x, p), label=p)    
        ax.legend(title='Gammar')    
        ax.set(xlabel='x')    
        ax.set(ylabel='y')    
        ax.autoscale(tight=True)    

plt.savefig('fig3.jpg', dpi=300)
plt.show()

列表

创建

lst = [] # 方括号
list2 = list([])
  1. 有序
  2. 索引从0开始,-1从后开始
  3. 可存储重复数据
  4. 任意数据混存
  5. 动态分配和回收内存

获取

正 向 : 0 — N − 1 负 向 : − N   − 1 正向:0—N-1 负向:-N~-1 0N1N 1

lst.index() #查询列表元素的索引,相同的话只返回相同元素的第一个索引
lst.index('hello',1,3) #在指定范围查找

切片操作

lst[start:stop:step]
lst[::-1]
for item in lst:
	print(item)

列表元素操作

lst.append(100) # 添加
lst.extent(lst2)  # 向列表末尾一次性添加多个
lst.insert(1,100) #在1的位置添加100
lst[1:]=lst3 # 一次性添加多个
lst.remove() #根据元素移除
lst.pop() # 根据索引移除
lst[1:3] = []
lst.clear() #清除列表中的所有元素

del lst #直接删除列表对象


排序

lst = [20,30,60,10]
lst.sort()  # 默认从小到大,排序不产生新的列表
lst.sort(reverse=True)  # 降序排序

# 使用内置函数,产生新的列表

new_lst = sorted(lst)  


列表生成式

lst=[i*i for i in range(1,10)]

字典

dict key:value
无序

# 使用{}定义
sorce = {'a':100, 'b':90}

dict(name='a', score = 100)

获取字典中的元素

score['a']  # 键不存在会报错
score.get('a')

删除键

del score['a'] #
score.clear() 清空

获取字典视图

keys = score.keys() # 获取所有的键
values = score.values() #获取所有的值

items = score.items() #列表由元组组成

for item in score:
	print(item, score.get(item))

可变序列 列表、字典

  1. 占用较大内存,空间换时间
  2. 键和值成对,值可以重复
  3. 无序的
  4. 动态伸缩的
fruit = ['apple', 'banana', 'orage']
prices = [10,20,30]
d = {item.upper():price  for item,price in zip(fruit,prices)}
print(d)

# upper()字符串中字母由小写变为大写
zip()

集合

集合——可变类型的序列,是没有value的字典
元素不允许重复

s = {2,3,5}
s = set(range(5))
print(s,type(s))

新增或删除

s.add() #一次添加一次
s.update() #至少一个
s.remove()
s.discard() # 这个,不抛异常
s.pop() #不加参数,
s.clear() # 清空

集合间关系
返回为true or false

===
s2.issubset() #子集
#超集
s1.issuperset()
#是否含有交集
s2.isdisjoint(s3) 

数学操作

s1 & s2
s1.intersection(s2)

s1 | s2
s1.union(s2)

#差集
s1.difference(s3)
s1 - s2

#对称差集
s1.symmetric_difference(s2))

集合生成式

s = {i*i for i in range(10)}

元组

# ()
d = ('w', 'e',20)  #小括号可省略

#只有一个元素时要加上,
t = (10,)
# 内置函数
tuple('w', 'e',20)

元组中的元素不可变
元组遍历

print(t[0])

for item in t:
	print(item)

在这里插入图片描述

字符串

字符串驻留机制

对相同的字符串只保留一份(交互模式,pycharm内部会调制不行)

  • 字符串长度为0或1
  • 符合标识符
  • 编译时驻留,运行时不驻留
  • 【5,256】之间整数
id() #查看内存中地址

拼接

join 优于 +

查找

s.index('lo')
s.find('lo')  #建议find,找不到会返回-1

#逆向
s.rindex('lo')
s.rfind('lo')

大小写

转换成大小写地址发生变化

s.lower()
s.upper()
swapcase()大小写互换
capitalize()第一个字符大写,其余小写
title()每个单词第一个字母大写,其余小写

左右对齐

s.center(20,'*')

在这里插入图片描述
字符串分割

s.split() #默认分隔符是空格
s.rsplit() #从右侧开始切分

判断字符串操作
在这里插入图片描述

字符串替换

s.replace('a','b') #被替换字符串、替换字符串、替换最大次数

字符串拼接

'*'.join()

字符串比较

从第一个字符依次比较下去

ord('a')  97
chr(97)  a

字符串切片

sq = s[:5]
se = s[start:end:step] # 默认从字符串第一个开始

格式化字符串

%s 字符串 %d %i 整数 %f 浮点数
print(我叫{0},今年{1}岁.format(name,age))

print('我叫{0},今年{1}岁'.format(name,age))
print('我叫%s,今年%d岁' % (name,age))
print('%10d' % 99)  #占10个宽度 。3表示小数点后三位

编码-解码

s ='hello world'
byte = s.encode(encoding='GBK')
byte.decode(encoding='GBK')

函数

位置参数 根据位置对应传参
关键字参数,根据名称进行传参

参数定义

#个数可变的位置参数 只能是一个 结果是一个元组
def fun(*args):
	print(args)

# 个数可变的关键字形参  只能是一个,结果是一个字典
def fun(**args):

参数调用

def fun(a,b,c):
	print('a=',a)

fun(10,20,30) 
lst=[11,22,33]
fun(*lst)#函数调用时,将列表中的每个元素转换为位置实参传入
fun(a-10,c=20,b=30) # 关键字传参
dic={'a':11,'b',22,'c',33}
fun(**dic)  # 将字典中的键值对都转为关键字传参


lst=[1,2,3]
fun(*lst)  #

# c只能采用关键字实参

def fun(a,b,*,c):
	print('a=',a)
函数内部glob声明,就是全局变量

递归函数

套娃

占用内存多,效率低下
思路和代码简单

一切皆对象

类名有一个或多个单词组成,每个单词首字母大写

“实例方法:不需要访问实例属性
类方法:不需要访问类属性
静态方法:不需要访问类方法也不需要访问实例属性
@staticmethod
不需要创建类对象
通过类名.调用静态方法”

class Student:

	# 类之内的变量叫类属性
	#初始化方法
	def __init__(self, name,age):  
	#self.name 实例属性
		
	#实例
	#静态方法
	@staticmethod
	def method():  #不能有self
	#classmethod
	def cm(cls):
	


#类之外 函数

stu = Student(‘a’.20)
print(stu)
输出是的类的地址(十六进制)

对象名.方法()

类名.方法(类对象)

类属性方法外的变量被类的所有对象共享
类方法@classmethod类名直接访问
静态方法@staticmethod类名直接访问

动态绑定属性和方法

#定义在类之外的称为函数
动态绑定方法

stu1.show() = show()

面向对象三大特征
1.封装 提高安全性
2. 继承 提高复用性
3. 多态 提高可扩展性

class Student:
	def __init__(self, name, age):
		self.name = name

		self.__age = age # 私有变量

stu = Student('a',10)

print(stu.__age) # 不可以访问
print(stu._Student__age) #可以这样访问

继承

super().__init__()  #继承父类的方法

方法重写

def info():
	super().info()  #继承父类
dir(类对象) #查看所有的属性

__str__()  #返回一个对于“对象的描述”

多态

在这里插入代码片

静态语言 JAVA实现多态的三个必要条件:

  1. 继承
  2. 方法重写
  3. 父类引用指向子类对象

动态语言 python:有没有这个函数

  __dict__ 

在这里插入图片描述

文件读写

IO操作 队列 先进先出

Created with Raphaël 2.3.0 操作文件 打开或新建文件 读写文件 关闭资源
file = open(filename,[mode, encoding ])
print(file.readlines())

在这里插入图片描述

文件对象常用方法

read([size])  #从文件中读取size个字节的内容,弱省略则读取所有内容

readline()  #读取一行内容
readlines()  #每一行作为独立的字符串对象
write()  # 字符串写入
writelines()  #字符串列表写入

seek(offset,[,whence])  #文件指针移动到新的位置
whence: 0代表从文件头开始计算(默认)
1:从当前位置开始计算
2:从文件末尾开始计算

tell()  #返回文件指针的当前位置
flush() #把缓冲区内容进文件,但不关闭文件
close()  #释放文件资源

上下文管理器

with语句可以自动管理上下文资源,无论什么原因跳出with块,都能保证文件正确的关闭

在这里插入图片描述

os.system('calc.exe')
os.startfile('') #调用可执行文件

在这里插入图片描述
在这里插入图片描述

lst = os.walk(path)

for dirpath,diename,filename in lst:
	for dir in dirname:
		print(os.path.join(dirpath,dir)  #返回所有的子路径
	for file in filename:
		print(os.path.join(dirpath,file) #返回所有的文件名

python >模块> 函数 类 语句

自定义模块

import 模块 as 别名 只能跟包名或模块名

from 模块名称 import 函数、变量、类

可以导入包、模块、函数、变量

if __name_ == '__main__':

包 中会包含__init__.py

在这里插入图片描述

bug

语法错误

  1. 末尾冒号,

在这里插入图片描述

思路不清

  1. print() 输出中间过程
  2. 注释部分

异常处理

捕获异常的顺序先子类后父类

try:
 	
except   :

没有抛出异常,执行else块,否则执行except

try:
	n1 = int(input('输入整数'))
	n2 = int(input('输入整数'))
	result = n1/n2
except BaseException as e:
	print(e)
else:
	print(result)

finally 无论是否出错,都会执行

有异常
无异常
try
except
finally
else
异常类型描述
ZeroDivisionError被0除
IndexError索引不存在
KeyError键不存在
NameError未声明、初始化对象
SyntaxError语法错误
ValueError传入无效参数
使用tracback模块打印异常信息

import traceback
try:
	print('1.--------------')
except:
	traceback.print_exc()
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值