python小知识
Python小知识
浮点数注意事项
# 浮点数精度问题
from decimal import Decimal
print(0.1 + 0.1) # 0.2
print(0.1 + 0.2) # 0.30000000000000004
print(Decimal("0.1") + Decimal("0.2")) # 0.3,注意:参数是字符串
jsonpath提取数据
# pip install jsonpath
from jsonpath import jsonpath
actual = {"data": {"msg": "The verification code is wrong or expired"}, "code": 200}
expected = {"msg": "The verification code is wrong or expired", "code": 200}
for key, value in expected.items():
print(jsonpath(actual, f"$..{key}")) # 以列表展示
print(jsonpath(actual, f"$..{key}")[0])
assert jsonpath(actual, f"$..{key}")[0] == expected[key]
expected = {"$..msg": "The verification code is wrong or expired", "$..code": 200}
for key, value in expected.items():
actual_value = jsonpath(actual, key)[0]
print(actual_value)
assert actual_value == value
数据替换
import json
import string
# 数据替换
old_headers = '{"Authorization": "new token", "uuid": "new uuid"}'
headers = json.loads(old_headers)
headers["Authorization"] = "adifhsjfnaksldf"
headers["uuid"] = "xxx"
print(headers)
# 新的办法
# old_headers = '{"Authorization": "${token}", "uuid": "${uuid}", "a": "b"}'
old_headers = '{"Authorization": "${token}", "uuid": "old uuid", "a": "${b}"}'
new_data = {"token": "my token", "uuid": "my uuid", "b": "new c"}
t = string.Template(old_headers)
new_headers = t.substitute(new_data)
print(new_headers)
# 封装替换数据的函数
def replace_data(old: str, new: dict):
t = string.Template(old)
new_headers = t.substitute(new)
return new_headers
if __name__ == '__main__':
print(replace_data(old_headers, new_data))
old_headers = '{"Authorization": "token", "uuid": "old uuid", "a": "b"}' # 替换的数据为字符串类型
new_data = {}
# 数据替换的用法,如果old_headers没有需要替换的数据,new_data数据为空,得到的new_headers为old_headers数据
t = string.Template(old_headers)
new_headers = t.substitute(new_data)
print(new_headers)
print(type(new_headers)) # 生成的也是字符串类型化
print(json.loads(new_headers)) # 转换成字典类型的数据
print(type(json.loads(new_headers)))
yaml学习
-
支持的数据类型:字典、列表、字符串、布尔值、整数、浮点数、Null、时间等
-
基本语法规则:
- 大小写敏感
- 使用缩进表示层级关系
- 相同层级的元素左侧对齐
- 键值对用冒号 “:” 结构表示,冒号与值之间需用空格分隔
- 数组前加有 “-” 符号,符号与值之间需用空格分隔
- None值可用null 和 ~ 表示
- 多组数据之间使用3横杠---分割
#表示注释,但不能在一段代码的行末尾加 #注释,否则会报错
读取yaml文件
# 注释
# 后面的字符串表示建议带引号
# 冒号后面一定要空格
name: "yu"
name1: yu
age: 26
femail: true
# python中的字典
database: { "host": "http://xxx.com", "port": 3306 }
database1:
host: "http://xxx.com"
port: 3306
# 列表
hobby: [ "music", "电影" ]
hobby1:
- "music"
- "电影"
# pip install pyyaml
import yaml
# 读取yaml
with open("read.yaml", encoding="utf-8") as f:
# print(f.read())
data = yaml.safe_load(f.read())
print(data, type(data))
# 结果:
# {'name': 'yu', 'name1': 'yu', 'age': 26, 'femail': True, 'database': {'host': 'http://xxx.com', 'port': 3306: None}, 'database1': {'host': 'http://xxx.com', 'port': 3306}, 'hobby': ['music', '电影'], 'hobby1': ['music', '电影']} <class 'dict'>
import yaml
# 读取yaml
with open("read.yaml", encoding="utf-8") as f:
result = yaml.load(f.read(), Loader=yaml.FullLoader)
print(result, type(result))
# 结果:
# {'name': 'yu', 'name1': 'yu', 'age': 26, 'femail': True, 'database': {'host': 'http://xxx.com', 'port: 3306': None}, 'database1': {'host': 'http://xxx.com', 'port': 3306}, 'hobby': ['music', '电影'], 'hobby1': ['music', '电影']} <class 'dict'>
读取yaml元组
!!python/tuple # yaml中使用!!对数据类型进行转换,yaml中tuple由list转换而来
- pa
- ho
- le
import yaml
with open("yaml_tuple.yaml", "r", encoding="utf-8") as f:
result = yaml.load(f.read(), Loader=yaml.FullLoader)
print(result, type(result))
# 结果:
# ('pa', 'ho', 'le') <class 'tuple'>
读取yaml多组数据
os: Android
osVersion: 10
account1:
username1: xiaoqq
password1: 123456
--- # 每组数据之间需要“---”分隔
os: ios
osVersion: 12
account1:
username2: lei
password2: 888888
import yaml
with open("multi_data.yaml", "r", encoding="utf-8") as f:
result = yaml.load_all(f.read(), Loader=yaml.FullLoader)
print(result, type(result))
for i in result:
print(i)
# 结果:
<generator object load_all at 0x000002172EF122D0> <class 'generator'>
{'os': 'Android', 'osVersion': 10, 'account1': {'username1': 'xiaoqq', 'password1': 123456}}
{'os': 'ios', 'osVersion': 12, 'account1': {'username2': 'Lilei', 'password2': 888888}}
写入yaml单组数据
import yaml
apiData = {
"page": 1,
"msg": "地址",
"data": [{
"id": 1,
"name": "学校"
}, {
"id": 2,
"name": "公寓"
}, {
"id": 3,
"name": "流动人口社区"
}],
}
with open("write.yaml", "w", encoding="utf-8") as f:
yaml.dump(apiData, f, allow_unicode=True)
with open("write.yaml", "r", encoding="utf-8") as f:
result = yaml.load(f.read(), Loader=yaml.FullLoader)
print(result, type(result))
写入yaml多组数据
import yaml
apiData1 = {
"page": 1,
"msg": "地址",
"data": [{
"id": 1,
"name": "学校"
}, {
"id": 2,
"name": "公寓"
}, {
"id": 3,
"name": "流动人口社区"
}],
}
apiData2 = {
"page": 2,
"msg": "地址",
"data": [{
"id": 1,
"name": "酒店"
}, {
"id": 2,
"name": "医院"
}, {
"id": 3,
"name": "养老院"
}],
}
with open("multi_data.yaml", "w", encoding="utf-8") as f:
yaml.dump_all([apiData1, apiData2], f, allow_unicode=True)
with open("multi_data.yaml", "r", encoding="utf-8") as f:
result = yaml.load_all(f,Loader=yaml.FullLoader)
for i in result:
print(i)
按照指定格式生成当前时间
import time
print(time.strftime("%Y-%m-%d_%H-%M-%S %a %p", time.localtime())) # 打印当前时间:2023-08-29_22-23-12 Tue PM
随机生成手机号
# 生成一个手机号码
import random
from faker import Faker
def generate_mobile():
phone = "1" + random.choice(["3", "5", "6", "7", "8", "9"])
for i in range(9):
num = random.randint(0, 9)
phone += str(num)
return phone
fk = Faker(locale="zh-CN") # 设置国家
if __name__ == '__main__':
print(generate_mobile())
print(fk.phone_number()) # 手机号
print(fk.ssn()) # 身份证号码
print(fk.credit_card_number()) # 银行卡号
print(fk.address()) # 地址
print(fk.email()) # 邮箱
print(fk.profile()) # 人物简介
print(fk.random_int(min=1,max=55)) # 随机生成整数
print(fk.pystr()) # 生成随机的字符串
print(fk.sentence()) # 随机生成一句话
print(fk.text()) # 随机生成一篇短文
a = "abcdefghijklmn"
print(random.sample(a,5)) # 随机打印 ['d', 'm', 'h', 'j', 'f']
# 官方网站
# https://pypi.org/project/Faker/
getattr()函数
class A(object):
bar = 1
def c(self, s):
return s
a = A()
print(getattr(a, "bar")) # 获取bar的属性,bar为字符串类型,不存在会处发生异常
print(getattr(a, "b", 3)) # 获取b的属性,属性b不存在,但设置了默认值
print(getattr(a, "c")("d")) # 获取c方法的返回值,并传递参数
mysql数据库读取
# pip install pymysql
import pymysql
from pymysql.cursors import DictCursor # 将读取的数据以字典的形式展示
class DB:
def __init__(self):
self.conn = pymysql.connect(host="数据库地址",
port=数据库端口号,
user="用户名",
password="密码",
database="数据库名称",
cursorclass=DictCursor) # 使用字典的游标
def query_one(self, sql):
cursor = self.conn.cursor() # 建立游标
cursor.execute(sql) # 查询
result = cursor.fetchone() # 获取查询的第一个结果
cursor.close() # 关闭游标
return result
def query_all(self, sql):
cursor = self.conn.cursor()
cursor.execute(sql)
result = cursor.fetchall() # 获取查询的全部结果
cursor.close()
return result
def close(self):
"""关闭数据库"""
self.conn.close()
if __name__ == '__main__':
db = DB()
result = db.query_all("SELECT id, user_phone FROM tz_sms_log LIMIT 5;")
print(result)
db.close()
openpyxl读取Excel表格指定工作簿的全部数据
# pip install openpyxl
import openpyxl
from openpyxl.worksheet.worksheet import Worksheet
# 加载工作簿
wb: openpyxl.Workbook = openpyxl.load_workbook("py.xlsx")
print(wb)
print(wb.sheetnames) # 以列表形式打印所有sheet工作簿的名称
# 选择默认的 sheet 表格
# sheet = wb.active
# 指定某个单元格
sheet: Worksheet = wb["test"]
print(sheet)
print(sheet.cell(row=1, column=1).value) # 获取第一行第一列的数据
print(sheet["C5"].value) # 获取单元格C5的值
# 获取单元格B3到D7的值
cells = sheet["B3:D7"]
print(cells)
for cell_rows in cells: # 行
for cell_colums in cell_rows: # 列
print(cell_colums.value, end=" ")
print()
# 获取D列的所有值
for i in sheet["D"]:
print(i.value)
# 获取5行的所有值
for i in sheet[5]:
print(i.value)
# 获取所有的数据
items = list(sheet.values)
print(items)
# title = items[0]
# new_list = []
# for item in items[1:]:
# info = dict(zip(title, item))
# new_list.append(info)
# print(new_list)
title = items[0]
new_list = [dict(zip(title, item)) for item in items[1:]] # 第一行是标题,以字典的形式打印所有的数据
print(new_list)
封装
import openpyxl
# 加载工作簿
def read_excel(file, sheet_name):
"""读取excel表格"""
wb = openpyxl.load_workbook(file)
sheet = wb[sheet_name]
items = list(sheet.values)
# 转成 dict
title = items[0]
new_list = [dict(zip(title, item)) for item in items[1:]]
return new_list
路径处理
import pathlib
# 获取当前文件的路径
current_file = pathlib.Path(__file__).absolute()
print(current_file)
# 获取上一级目录
parent = current_file.parent
print(parent)
# 上上一级
print(current_file.parent.parent)
# 路径的拼接
excel_file = parent / "py.xlsx"
print(excel_file)
正则表达式
import re
a = 'data-report-click="{"mod":"","dest":"https://gitcode.net?utm_source=csdn_toolbar","spm":"3001.6768"}"'
result = re.search("https://(.*?);", a)
print(result.group(), type(result.group())) # https://gitcode.net?utm_source=csdn_toolbar" <class 'str'>
print(result.group(1), type(result.group(1))) # gitcode.net?utm_source=csdn_toolbar" <class 'str'>
line = "Cats are smarter than dogs";
searchObj = re.search(r'(.*) are (.*?) ', line, re.M | re.I)
print(searchObj) # <re.Match object; span=(0, 17), match='Cats are smarter '>
if searchObj:
print("searchObj.group() : ", searchObj.group()) # searchObj.group() : Cats are smarter
print("searchObj.group(1) : ", searchObj.group(1)) # searchObj.group(1) : Cats
print("searchObj.group(2) : ", searchObj.group(2)) # searchObj.group(2) : smarter

浙公网安备 33010602011771号