返回

Python 相关

目录

基础

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# 算数运算符
+-*/(a**b, b次幂)(// 整除)
# 成员运算符
in , not in

# 字符串运算
print(str)                 # 输出字符串
print(str[0:-1])           # 输出第一个到倒数第二个的所有字符
print(str[0])              # 输出字符串第一个字符
print(str[2:5])            # 输出从第三个开始到第六个的字符(不包含)
print(str[2:])             # 输出从第三个开始后的所有字符
print(str[1:5:2])          # 输出从第二个开始到第五个且每隔一个的字符(步长为2)
print(str * 2)             # 输出字符串两次
print(str + '你好')        # 连接字符串
'''
string1
string2
'''

a= True
b= False

list = [0, 1, 2, 3, 4]
Tuple = (1, 2, 3);
set = {'a', 'a', 'b', 'c', 'd', 'd'}

a = set('abracadabra')
b = set('alacazam')
print(a - b)     # a 和 b 的差集
print(a | b)     # a 和 b 的并集
print(a & b)     # a 和 b 的交集
print(a ^ b)     # a 和 b 中不同时存在的元素

dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)])

# bytes 类型
x = bytes("hello", encoding="utf-8")

# if
if num == 3:
    print 'boss'        
elif num == 2:
    print 'user'
else:
	fn();

# while
while i < 10:   
    i += 1
    if i%2 > 0:     # 非双数时跳过输出
        continue
    else: 
    	break
    print i
else:
	print i

# for
fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print ('当前水果 : %s' % fruits[index])

# Number
int(x [,base ])         将x转换为一个整数  
float(x )               将x转换到一个浮点数  
complex(real [,imag ])  创建一个复数  
str(x )                 将对象 x 转换为字符串  
repr(x )                将对象 x 转换为表达式字符串  
eval(str )              用来计算在字符串中的有效Python表达式,并返回一个对象  
tuple(s )               将序列 s 转换为一个元组  
list(s )                将序列 s 转换为一个列表  
chr(x )                 将一个整数转换为一个字符  
ord(x )                 将一个字符转换为它的整数值  
hex(x )                 将一个整数转换为一个十六进制字符串  
oct(x )                 将一个整数转换为一个八进制字符串  

# 三角函数

acos(x)	    返回x的反余弦弧度值
asin(x)	    返回x的反正弦弧度值
atan(x)	    返回x的反正切弧度值
atan2(y, x)	返回给定的 X  Y 坐标值的反正切值
cos(x)	    返回x的弧度的余弦值
hypot(x, y)	返回欧几里德范数 sqrt(x*x + y*y)
sin(x)	    返回的x弧度的正弦值
tan(x)	    返回x弧度的正切值
degrees(x)	将弧度转换为角度,如degrees(math.pi/2)  返回90.0
radians(x)	将角度转换为弧度

# 字符串格式化
# usage:
print ("我叫 %s 今年 %d 岁!" % ('小明', 10))
 %c	 格式化字符及其ASCII码
 %s	 格式化字符串
 %d	 格式化整数
 %u	 格式化无符号整型
 %o	 格式化无符号八进制数
 %x	 格式化无符号十六进制数
 %X	 格式化无符号十六进制数大写
 %f	 格式化浮点数字可指定小数点后的精度
 %e	 用科学计数法格式化浮点数
 %E	 作用同%e用科学计数法格式化浮点数
 %g	 %f和%e的简写
 %G	 %F  %E 的简写
 %p	 用十六进制数格式化变量的地址

 # 列表
 [['a', 'b', 'c'], [1, 2, 3]]
 x[0][1]
 ## 列表比较
 # 导入 operator 模块
import operator
a = [1, 2]
b = [2, 3]
c = [2, 3]
print("operator.eq(a,b): ", operator.eq(a,b))
print("operator.eq(c,b): ", operator.eq(c,b))
## 方法
1	list.append(obj)
在列表末尾添加新的对象
2	list.count(obj)
统计某个元素在列表中出现的次数
3	list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值用新列表扩展原来的列表
4	list.index(obj)
从列表中找出某个值第一个匹配项的索引位置
5	list.insert(index, obj)
将对象插入列表
6	list.pop([index=-1])
移除列表中的一个元素默认最后一个元素),并且返回该元素的值
7	list.remove(obj)
移除列表中某个值的第一个匹配项
8	list.reverse()
反向列表中元素
9	list.sort( key=None, reverse=False)
对原列表进行排序
10	list.clear()
清空列表
11	list.copy()
复制列表

# With
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
# 文件已自动关闭

# 函数
def change(a):
    print(id(a))   # 指向的是同一个对象
    a=10
    print(id(a))   # 一个新对象
a=1
print(id(a))
change(a)

def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]

# lambda
sum = lambda arg1, arg2: arg1 + arg2
print ("相加后的值为 : ", sum( 10, 20 ))

# 装饰器
def decorator_function(original_function):
    def wrapper(*args, **kwargs):
        # 这里是在调用原始函数前添加的新功能
        before_call_code()
        
        result = original_function(*args, **kwargs)
        
        # 这里是在调用原始函数后添加的新功能
        after_call_code()
        
        return result
    return wrapper
@decorator_function
def target_function(arg1, arg2):
# 带参数的写法
def repeat(num_times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def say_hello():
    print("Hello!")

say_hello()

# 自定义模块
## // fib.py
# 斐波那契(fibonacci)数列模块
 
def fib(n):    # 定义到 n 的斐波那契数列
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()
 
def fib2(n): # 返回到 n 的斐波那契数列
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result
## 使用
import fub
fibo.fib(1000)

from math import sqrt as square_root

文件操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import os

class ScriptParser:
    def __init__(self, input_path, output_path):
        self.input_path = input_path
        self.output_path = output_path

    def read_script(self):
        """从文件中读取脚本内容"""
        try:
            with open(self.input_path, 'r', encoding='utf-8') as file:
                lines = file.readlines()
            return lines
        except FileNotFoundError:
            print(f"错误:文件 {self.input_path} 未找到。")
            return []
        except Exception as e:
            print(f"读取文件时发生错误:{e}")
            return []

    def process_script(self, lines):
        """处理每一行,在其后添加“翻译:”行"""
        processed_lines = []
        for line in lines:
            line = line.rstrip('\n')
            processed_lines.append(line + '\n')
            processed_lines.append("翻译:\n")
        return processed_lines

    def write_script(self, content):
        """将处理后的内容写入新文件"""
        try:
            with open(self.output_path, 'w', encoding='utf-8') as file:
                file.writelines(content)
            print(f"文件已成功写入到 {self.output_path}")
        except Exception as e:
            print(f"写入文件时发生错误:{e}")

    def run(self):
        """运行解析器流程"""
        if not os.path.exists(self.input_path):
            print("输入文件不存在,请检查路径。")
            return

        print("开始读取脚本...")
        lines = self.read_script()

        print("开始处理脚本...")
        processed_lines = self.process_script(lines)

        print("开始写入翻译版脚本...")
        self.write_script(processed_lines)


def main():
    # 示例路径(请根据实际情况修改)
    input_file = "script.txt"
    output_file = "translated_script.txt"

    # 创建解析器实例并运行
    parser = ScriptParser(input_file, output_file)
    parser.run()


if __name__ == "__main__":
    main()

模块

math

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
math.pi	    # 圆周率 π ≈ 3.141592653589793
math.e	    # 自然对数的底 e ≈ 2.718281828459045
math.tau	# τ = 2π ≈ 6.283185307179586
math.inf	# 表示正无穷大(float 类型)
math.nan	# 表示“非数字”(Not a Number)

abs(x)	        返回数字的绝对值如abs(-10) 返回 10
ceil(x)	        返回数字的上入整数如math.ceil(4.1) 返回 5
cmp(x, y)	    如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
exp(x)	        返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045
fabs(x)	        以浮点数形式返回数字的绝对值如math.fabs(-10) 返回10.0
floor(x)	    返回数字的下舍整数如math.floor(4.9)返回 4
log(x)	        如math.log(math.e)返回1.0,math.log(100,10)返回2.0
log10(x)	    返回以10为基数的x的对数如math.log10(100)返回 2.0
max(x1, x2,...)	返回给定参数的最大值参数可以为序列
min(x1, x2,...)	返回给定参数的最小值参数可以为序列
modf(x)	        返回x的整数部分与小数部分两部分的数值符号与x相同整数部分以浮点型表示
pow(x, y)	    x**y 运算后的值
round(x [,n])	返回浮点数x的四舍五入值如给出n值则代表舍入到小数点后的位数
sqrt(x)	        返回数字x的平方根

os

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import os
current_directory = os.getcwd()
print("当前工作目录:", current_directory)

os.chdir("/path/to/new/directory")
print("新的工作目录:", os.getcwd())

files_and_dirs = os.listdir()
print("目录内容:", files_and_dirs)

os.mkdir("new_directory")
os.rmdir("new_directory")
os.remove("file_to_delete.txt")
os.rename("old_name.txt", "new_name.txt")
# 获取环境变量
home_directory = os.getenv("HOME")
print("HOME 目录:", home_directory)
# sh
os.system("ls -l")

re(正则表达式)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
re.search() 
# 函数用于在字符串中搜索正则表达式的第一个匹配项。与 re.match() 不同,re.search() 不要求匹配从字符串的起始位置开始。
pattern = r"world"
text = "hello world"
match = re.search(pattern, text)

re.sub() 
# 函数用于替换字符串中与正则表达式匹配的部分。
pattern = r"apple"
text = "I have an apple."

new_text = re.sub(pattern, "banana", text)
print("替换后的文本:", new_text)

json

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import json
 
# Python 字典类型转换为 JSON 对象
data1 = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}
 
json_str = json.dumps(data1)  // 编码
print ("Python 原始数据:", repr(data1))
print ("JSON 对象:", json_str)
 
# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str) // 解码
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])

pyecharts

图表类型 pyecharts 类 包引入语句
折线图 Line from pyecharts.charts import Line
柱状图 Bar from pyecharts.charts import Bar
散点图 Scatter from pyecharts.charts import Scatter
饼图 Pie from pyecharts.charts import Pie
雷达图 Radar from pyecharts.charts import Radar
热力图 HeatMap from pyecharts.charts import HeatMap
K 线图 Kline from pyecharts.charts import Kline
箱线图 Boxplot from pyecharts.charts import Boxplot
地图 Map from pyecharts.charts import Map
词云图 WordCloud from pyecharts.charts import WordCloud
仪表盘 Gauge from pyecharts.charts import Gauge
漏斗图 Funnel from pyecharts.charts import Funnel
树图 Tree from pyecharts.charts import Tree
平行坐标系图 Parallel from pyecharts.charts import Parallel
桑基图 Sankey from pyecharts.charts import Sankey
地理坐标系图 Geo from pyecharts.charts import Geo
时间线图 Timeline from pyecharts.charts import Timeline
3D 散点图 Scatter3D from pyecharts.charts import Scatter3D
3D 柱状图 Bar3D from pyecharts.charts import Bar3D
3D 曲面图 Surface3D from pyecharts.charts import Surface3D
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from pyecharts import options as opts
from pyecharts.charts import Bar
# 内置主题类型可查看 pyecharts.globals.ThemeType
from pyecharts.globals import ThemeType

# 准备数据
x_data = ['一月', '二月', '三月', '四月', '五月']
y_data = [10, 20, 15, 25, 30]

# 创建柱状图
bar_chart = Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))  # 初始主题为亮色系
bar_chart.add_xaxis(x_data)
bar_chart.add_yaxis("销售额", y_data)

# 配置图表
bar_chart.set_global_opts(
    title_opts=opts.TitleOpts(title="月度销售额柱状图"),
    xaxis_opts=opts.AxisOpts(name="月份"),
    yaxis_opts=opts.AxisOpts(name="销售额(万元)"),
)

# 切换到暗色系主题
bar_chart.set_global_opts(theme=ThemeType.DARK)

# 渲染图表
bar_chart.render("themed_bar_chart.html")

zlib

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import zlib

# 要压缩的数据
data = b"This is some data that we're going to compress"

# 使用 zlib.compress() 压缩数据
compressed_data = zlib.compress(data)

print(f"Compressed data: {compressed_data}")

# 使用 zlib.decompress() 解压数据
decompressed_data = zlib.decompress(compressed_data)

print(f"Decompressed data: {decompressed_data}")

import zlib

# 创建一个压缩对象
compressor = zlib.compressobj()

# 分块压缩数据
compressed_chunks = []
for i in range(0, len(data), 10):
    compressed_chunks.append(compressor.compress(data[i:i+10]))
compressed_chunks.append(compressor.flush())

# 创建一个解压对象
decompressor = zlib.decompressobj()

# 分块解压数据
decompressed_chunks = []
for chunk in compressed_chunks:
    decompressed_chunks.append(decompressor.decompress(chunk))
decompressed_chunks.append(decompressor.flush())

# 验证解压后的数据是否和原始数据一致
assert b"".join(decompressed_chunks) == data

socket

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:client.py
 
import socket               # 导入 socket 模块
 
s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345                # 设置端口号
 
s.connect((host, port))
print s.recv(1024)
s.close()

创建虚拟对象

官方

miniconda

Numpy

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import numpy as np

# 创建数组
a = np.array([1, 2, 3])
b = np.array([[1, 2], [3, 4]])
c = np.zeros((3, 3))  # 创建一个3x3的全0数组
d = np.ones((2, 2))   # 创建一个2x2的全1数组
e = np.eye(3)         # 创建一个3x3的单位矩阵
f = np.arange(0, 10, 2)  # 从0到10(不包含),步长为2的数组
g = np.linspace(0, 10, 5)  # 在0到10之间生成5个均匀分布的样本

# 索引和切片
print("b[0, 1] =", b[0, 1])  # 获取b的第一行第二列元素
print("b[:, 1] =", b[:, 1])  # 获取b的所有行的第二列

# 基本运算
print("a + a =", a + a)  # 数组加法
print("a * 2 =", a * 2)  # 数组乘以标量
print("np.dot(b, [[1], [2]]) =", np.dot(b, [[1], [2]]))  # 矩阵乘法

# 广播机制
print("b + a =", b + a)  # 尝试对不同形状的数组执行加法

# 聚合操作
print("a.sum() =", a.sum())  # 数组元素总和
print("b.min() =", b.min())  # 数组最小值
print("b.mean() =", b.mean())  # 数组平均值

# 线性代数运算
h = np.array([[1, 2], [3, 4]])
i = np.linalg.inv(h)  # 求逆矩阵
print("Inverse of h:\n", i)
print("Check inverse:", np.dot(h, i))  # 验证逆矩阵,结果应接近单位矩阵

# 改变数组形状
j = np.arange(6).reshape((2, 3))  # 重塑数组形状
print("Reshaped array:\n", j)

# 随机数生成
k = np.random.rand(2, 3)  # 生成2x3的随机数数组
print("Random array:\n", k)

# 定义两个三维向量
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# 计算点乘
dot_product = np.dot(a, b)
print("Dot product:", dot_product)

# 计算叉乘
cross_product = np.cross(a, b)
print("Cross product:", cross_product)

PyQt

openCV

Pillow

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from PIL import Image
import numpy as np

# 打开图像文件
img = Image.open("1.png")
# 转换为numpy数组以进行处理
imgArr = np.array(img)

# 确保图像是RGB图像
if len(imgArr.shape) == 3:
    # 分离RGB通道
    r, g, b = imgArr[:,:,0], imgArr[:,:,1], imgArr[:,:,2]
    # 应用公式转换为灰度
    grayImgArr = 0.299 * r + 0.587 * g + 0.114 * b
else:
    grayImgArr = imgArr

# 将numpy数组转换回图像并显示
gray_img = Image.fromarray(np.uint8(grayImgArr))
gray_img.thumbnail((128,128));
gray_img.show()

# 复制子矩形
box = (100, 100, 400, 400)
region = im.crop(box)

region = region.transpose(Image.ROTATE_180) # 颠倒180度
box = (400, 400, 700, 700)  # 粘贴位置,像素必须吻合,300 * 300
im.paste(region, box)

r, g, b = im.split()
im = Image.merge("RGB", (b, g, r))

out = im.resize((128, 128))
out = out.rotate(45)
im.convert("L"); # 转换成灰阶

ImageFilter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from PIL import Image, ImageFilter
# 打开图像
image = Image.open("example.jpg")

# 应用高斯模糊
blurred = image.filter(ImageFilter.GaussianBlur(radius=2))

# 保存处理后的图像
blurred.save("blurred_example.jpg")

# 显示图像
blurred.show()

result = img.filter(ImageFilter.EDGE_ENHANCE) \
            .filter(ImageFilter.SHARPEN) \
            .filter(ImageFilter.GaussianBlur(0.5))
Licensed under CC BY-NC-SA 4.0