目录
2.1.6 strip() lstrip() rstrip()
5.1.7 count(value) 获取指定数据在列表中出现的次数
4、sorted(list, reverse=Ture)降序
7.3.1 在try模块连接资源在finally模块关闭资源
3. isinstance(instance, class)
一、入门
1.1 编辑器
编辑器:vscode
1.2 扩展工具
语法检查工具pylint
点击install即可
确认下当前使用的Python版本是不是3以上,之后点击install即可
如果代码有错误,代码行会飘红,点击View—— Problems(shift+ctrl+M)打开报错的详细信息框
命令策略面板Command Palette(shift+ctrl+P) ,输入linter
点击select linter
pylint 是最受欢迎和vscode中默认的语法检查工具
代码格式化工具pep8
:PEP 8 – Style Guide for Python Code | peps.python.org
命令策略面板Command Palette(shift+ctrl+P),打开面板输入format
最受欢迎和默认的代码格式化工具是autopep8,点击Yes即可安装pep8工具
再次打开命令策略面板Command Palette(shift+ctrl+P),输入format点击format document命令就可以对当前代码文件进行格式化。
可以对格式化时机进行设置,不能每次都要执行format document命令,设置操作如下:
这样当你保存文件时会自动完成格式化校验和修正。
代码运行扩展工具:code runner
点击install
以后需要运行代码时不需要输入Python xx.py,ctrl+alt+N(ios是Ctrl+option+N)即可
1.3 Python是怎么运行的
二、基本类型
number:int 和 float
boolean:True False
string:"Python Programming"
字符串中有特殊字符,如单引号 双引号 反斜杠等需要输出时,使用转义字符\即可
course = "Python \''Programming"
course = "Python \'Programming"
course = "Python \\Programming"
变量命名按照驼峰
2.1 字符串
2.1.1 字符串长度 len(str)
len()为Python内置函数,并非字符串特有
course = "Python Programming"
str_len = len(course)
2.1.2 获取指定位置的字符
获取数据指定下标指的方法是通用的,对列表 字典
course = "Python Programming"
# 获取下标0对应的字符
print(course[0])
# 获取字符串的最后一个字符
print(course[-1])
print(course[17])
2.1.3 切片
注意:切片可以得到一个全新的字符串,它有单独的存储地址,原来的父字符串不会有任何改变
course = "Python Programming"
# 获取course字符串从下标0开始到下标3,但不包含下标3对应字符的一段字符串------即Pyt
print(course[0:3])
print(course[:3])
# 注意切片不会影响course字符串本身
# 获取course字符串从下标3开始一直到末尾的一段字符串
# -----即hon Programming
print(course[3:])
# 获取course字符串从下标0开始,到下标8为止(不包括下标8对应字符),没3个取1个
# 下标0~下标8对应Python Pr,不包含8,则为Python P
# 取下标0 对应的P
# 向后数3个yth,3个取1个,取h
# 再向后数3个on ,3个取1个,取空格
# 再向后数只有1个字符P,所以不能继续
# 所以最后得到的是Ph
print(course[0:8:3])
# 复制一个和course字符串完全一样的子字符串,但对新字符串的改动不能影响到course字符串本身
new_str = course[:]
print(new_str)
# 注意不能使用赋值 new_str = course,因为course和new_str这样的变量名其实只是一个指针,指向的内存地址,该地址内存储的内容是字符串内容,使用赋值会导致 new_str 和 course 指向的是同一个内存地址
2.1.4 字符串拼接
方法一:sum_str = str1 + " " + str2
方法二:sum_str = f"{str1} {str2}"
# 字符串拼接
first = "John"
last = "Smith"
full_name = f"{first} {last}"
print(full_name)
2.1.5 字符串大小写转换
str.upper() ——字符串str全部变为大写
str.lower() ——字符串str全部变为小写
str.title() —— 字符串内单词的首字母都变为大写
原始字符串str在经过对应方法处理后得到的是一个新的字符串,存储在新的地址
原始字符串str没有任何改变
course = "python programming"
print("新的字符串是:", course.title())
print("原始字符串course是:", course)
2.1.6 strip() lstrip() rstrip()
不传参数就是去除空格和换行符
传参数就是去除指定字符串
str.strip() —— 去除字符串左右两侧多余的空格
str.lstrip() —— 去除字符串左侧多余的空格
str.rstrip() —— 去除字符串右侧多余的空格
slogen = "12I like learning21"
new_str = slogen.strip("12")
print(new_str) # I like learning
# 把“12”看成2个字符串“1” 和 “2”
# 所以slogen左右的12 21 都会被去除
course = " python programming "
print(course.strip())
2.1.7 str.count(str1)
计算子串str1在字符串中出现的次数
2.1.8 find() index() 查找子字符串
str.find(str1) —— 在str字符串中查找str1,如果找到了,就返回第一次匹配时对应的下标
如果没找到就返回-1
str.index(str1)—— 在str字符串中查找str1,如果找到了,就返回第一次匹配时对应的下标
如果没找到就返回ValueError
course = "python programming"
print(course.find("p"))
# 返回0
print(course.find("H"))
# 返回-1
print(course.find("pro"))
# 返回7
course = "python programming"
value = course.index("pro")
print(value) # 7
value2 = course.index("p")
print(value2) # 0
value3 = course.index("P")
# print(value3) # ValueError: substring not found
2.1.9 replace(old, new) 字符串替换
str.replace(oldStr, newStr) —— 用newStr 替换字符串str中的oldStr
course = "python programming"
print(course.replace("p", "hhhh"))
# 返回hhhhython hhhhrogramming
2.1.10 split() 字符串分割
slogen = "I like learning"
arr = slogen.split(" ")
print(arr) # ['I', 'like', 'learning']
str1 in str 判断str1是否是str的子字符串,是就返回True,不是就返回False
str1 not in str
course = "python programming"
print("pro" in course)
2.1.11 字符串遍历
2.2 number
2.2.1 数据类型介绍和算术运算符
整数 小数 复数a+bi
算数运算符:加+ 减- 乘* 除尽/ 除后取整// 除后取余% 取幂**
+= -= *= /= //= %= **=
print(10 + 3)
# 13
print(10 - 3)
# 7
print(10 * 3)
# 30
print(10 / 3)
# 3.3333333333333335
print(10 // 3)
# 3
print(10 % 3)
# 1
print(10 ** 3)
# 1000
x = 10
# x += 3
# x -= 3
# x *= 3
# x /= 3
# x //= 3
# x %= 3
x **= 3
print(x)
2.2.2 数字的相关方法
可以参考:math — Mathematical functions — Python 3.11.4 documentationPython3.9标准库math中的函数汇总介绍(53个函数和5个常数)_python的math库中的函数有哪些_昊虹AI笔记的博客-CSDN博客
round(num) —— 四舍五入取整
print(round(2.1))
# 2
print(round(2.6))
# 3
abs(num) —— 取num的绝对值
print(abs(-7.5))
# 7.5
print(abs(0))
# 0
导入数学模块 import math
math.ceil(num) —— 向上舍入到最接近的整数
import math
print(math.ceil(2.2))
# 3
input()获取用户输入内容以字符串形式存储,所以需要注意数据处理时进行类型转换。
x = input("x: ")
print(type(x))
y = int(x) ** 2
# 表准字符串输出print(f"")
print(f"x: {x}, y: {y}")
类型转换的方法有:
int(x)
float(x)
bool(x)
str(x)
2.3 bool类型
print(bool(0))
# 返回false
print(bool(''"))
# 返回false
2.4 字符串格式化
2.4.1 方式一
在字符串内(即引号内)使用%s %d %f 进行占位,后面使用按照占位顺序传入变量,并放在%()的括号内
2.4.2 方式二
快速字符串格式化:
f"ababbajajaik{变量名}"
这种方式不关心变量类型,同样也不会做变量精度的控制。
三、控制流
3.1 if 语句
if 条件1:
balabala
elif 条件2:
balabal
.
.
.
elif 条件n:
balabala
else:
如果以上条件判断都不满足,执行这里的逻辑
逻辑运算符and or not 可以在条件表达式中使用
random.random(): 返回随机生成的一个浮点数,范围在[0,1)之间
random.uniform(a, b): 返回随机生成的一个浮点数,范围在[a, b)之间
random.randint(a,b):生成指定范围内的整数
random.randint(0,100) 就是随机生成一个0~100的数,包括0和100
np.random.randint(0,10) 和上面作用一样, 左闭右开,包括0 不包括10
3.3 循环
3.2.1 for循环
for number in range(3):
# range(3)取值范围[0, 3) 即0 1 2
# range(1, 4)取值范围[1, 4) 即1 2 3
# range(1, 10, 2) 取值[1, 10) 且时隔1个数字取一个 即1 3 5 7 9
print("hello", number)
# 99乘法表
for row in range(1, 10):
for col in range(1, row+1):
print(f"{col} * {row} = {col * row}\t",end='')
# 在print方法里使用end=''实现不换行
# 一行结束时需要换行
print()
输出内容但是不换行:print(f"要输出的内容", end='')
3.2.2 while循环
while 条件表达式:
balabala
row = 1
while row < 10:
col = 1
while col <= row:
print(f"{col} * {row} = {col * row}\t", end='')
col += 1
print()
row += 1
3.3 无限循环
就是for或者while后面的条件永远是Ture,这个时候在循环体内需要设置其他判断,当满足这个判断时用break结束循环。
四、方法functions
4.1 方法声明和调用
def test():
balkabala
test()
4.2 含参数的方法
def test(参数1, 参数2, ...参数n):
balabal
hh
test(参数值1, 参数值2, ...参数值n)
4.3 方法的类型
4.3.1 执行指定功能
def greet(name):
print(f"hi {name}")
#执行完任务后,可能会把结果输出在终端或者什么也不输出
greet("mosh")
# 函数没有设置返回值时,python默认会返回None
函数说明文档:
4.3.2 返回计算结果
def get_greeting(name):
reurn f"hi {name}"
# 方法执行完后会返回结果
message = get_greeting("mosh")
方法可以有多个返回值,并且可以使用多个变量接收函数的返回值
4.4 方法的参数
4.4.1 位置参数
4.4.2 关键字参数
4.4.3 缺省参数
def test(teacher, course = "python"):
return f"{teacher} 负责 {course}"
test("mosh")
4.4.3 不定长参数
# 定义可变参数
def test(*numbers):
print(numbers)# 元组可以用于循环
sum = 0
for number in numbers:
sum += number
return sum
# 调用方法传递多个数据时,这些数据存储在 元组中,
# 元组中的元素是不允许修改和删除的,只能增加,如果非要删除只能把整个元组都删了
test(1, 2, 3, 4)
# 得到的是元组:(1, 2, 3, 4)
def save_user(**user):
print(user)
print(user["name"])
# 带2个*号的参数会存储在字典中 {key1 : value1, key2 : value2 },可以通过key访问字典内部的值
save_user(id = 1, name = "john", age = 22)
# 得到的是字典: {'id': 1, 'name': 'john', 'age': 22}
4.5 方法内变量的生效范围
定义在方法内部的变量是局部变量,生命周期仅限于方法内。
全局变量定义在方法外,在整个python文件都是生效的,除非必要尽量不要定义全局变量。
局部变量可以和全局变量同名,但最好不要这样做。
还有不要在方法内修改全局变量,容易把业务逻辑改坏。
message = "b"
def greet(name):
# global message 在方法内部使用全局变量,后面可以用message = "hello"随意修改全局变量的值,但是最好别修改
message = "a" # 可以定义局部变量名和全局变量同名 但是最好不要这样做
print(message)
greet("mosh") # 里面使用的是局部变量 打印"a"
print(message) # 打印的是全局变量 "b"
4.6 匿名函数
4.6.1 函数作为参数传递
4.6.2 lambda匿名函数
五、数据结构
5.1 list 列表
5.1.1 定义列表
# 定义列表
letters = ["a", "b", "c"]
# 列表内嵌套列表
matrix = [[0, 1], [2, 3]]
# 初始化一个含有100个0元素的列表
zeros = [0] * 100
print(zeros)
# 列表组合
combined = letters + matrix
print(combined)
# ['a', 'b', 'c', [0, 1], [2, 3]]
# 使用list()方法创建列表
numbers = list(range(3, 20, 2))
print(numbers)
# [3, 5, 7, 9, 11, 13, 15, 17, 19]
greet = list("hello mosh")
print(greet)
# ['h', 'e', 'l', 'l', 'o', ' ', 'm', 'o', 's', 'h']
print(len(greet))
# 10
5.1.2 获取列表指定下标内容
letters = ["a", "b", "c","d"]
# 获取列表指定下标的内容
print(letters[1])
# b
print(letters[-1])
# d
# 修改列表指定下标的值
letters[0] = "A"
print(letters)
# ['A', 'b', 'c', 'd']
5.1.3 列表的切片
letters = ["a", "b", "c","d"]
# 获取列表的一段数据作为新列表的内容
# new_letters = letters[0:3]
new_letters = letters[:3]
print(new_letters)
# ['A', 'b', 'c']
# new_letters = letters[0:]
# new_letters = letters[:4]
new_letters = letters[:]
print(new_letters)
# ['A', 'b', 'c', 'd']
new_letters = letters[::2]
print(new_letters)
# ['A', 'c']
print(letters)
# ['A', 'b', 'c', 'd']
numbers = list(range(20))
# 取偶数
new_numbers = numbers[::2]
print(new_numbers)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 列表逆序
new_numbers = numbers[::-1]
print(new_numbers)
# [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(numbers)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
5.1.3 把列表内元素赋值给多个变量
需要注意的是变量的个数和列表内元素个数要一致,或者使用可变数量的变量接收剩余列表元素
numbers = [1, 2, 3]
first, second, third = numbers
print(f"first = {first} second = {second} third = {third}")
# first = 1 second = 2 third = 3
numbers = [1, 2, 3, 4, 5, 6]
# 使用可变数量的变量third接收列表剩余元素
first, second, *third = numbers
# 赋值的时候third前面只能有一个星号
print(f"first = {first} second = {second} third = {third}")
# first = 1 second = 2 third = [3, 4, 5, 6]
# 注意:接收列表剩余多个元素的third也是一个列表
numbers = [1, 2, 3, 4, 5, 6]
# 如果只需要用到列表的第一个和最后一个元素
first, *others, last = numbers
print(f"first = {first} others = {others} last = {last}")
# first = 1 others = [2, 3, 4, 5] last = 6
5.1.4 列表内循环
# 列表用于循环体
letters = ["a", "b", "c"]
for letter in letters:
print(letter)
# a
# b
# c
# 获取列表元素的同时打印元素的下标
for index, letter in enumerate(letters):
print(f"index = {index} letter = {letter}")
# index = 0 letter = a
# index = 1 letter = b
# index = 2 letter = c
5.1.5 插入/删除列表元素
1、append(value) 在列表尾部插入数据
list.append(value)
letters = ["a", "b", "c"]
letters.append("d")
print(letters)
# ['a', 'b', 'c', 'd']
2、insert(i, value)在指定下标插入数据
list.insert(i, value)
letters.insert(1, "f")
print(letters)
# ['a', 'f', 'b', 'c', 'd']
3、pop() 删除列表末尾的数据
list.pop() pop()方法会把移除的数据元素返回
letters = ['a', 'f', 'b', 'c', 'd']
c = letters.pop()
print(c) # d
print(letters) # ['a', 'f', 'b', 'c']
4、pop(i) 删除指定下标数据
list.pop(i)
letters = ['a', 'f', 'b', 'c', 'd']
c = letters.pop(1)
print(c) # f
print(letters) # ['a', 'b', 'c', 'd']
5、remove(value) 删除指定数据
list.remove(value) 只会把列表中第一个匹配的数据删除,如果列表中有重复数据,剩余的数据会保留
letters =["a", "b", "c", "d", "b"]
letters.remove("b")
print(letters)
# ['a', 'c', 'd', 'b']
6、del 删除指定下标数据
del list[i] 删除指定下标的元素
letters =["a", "b", "c", "d", "b"]
del letters[1]
print(letters)
# ['a', 'c', 'd', 'b']
del list[n:m] 删除下标n到下标m-1对应的元素值 n < m
letters =["a", "b", "c", "d", "b"]
# 删除列表内连续几个数据
del letters[0:2]
# 删除的是下标0 1对应的数据,不包括下标2的数据
print(letters)
# ['c', 'd', 'b']
7、clear() 清空列表
list.clear()
letters =["a", "b", "c", "d", "b"]
letters.clear()
print(letters)
# []
5.1.6 index() 查找指定数据在列表中的下标
index("目标值") 只会返回从左匹配的第一个匹配成功的数据下标
如果查找的数据在列表中没有则会报ValueError
letters =["a", "b", "c", "d", "b"]
print(letters.index("b"))
# 1
print(letters.index("f"))
# ValueError: 'f' is not in list
为了避免因为查找额数据在列表中不存在导致的报错,可以加上if判断
letters =["a", "b", "c", "d", "b"]
if "b" in letters:
print(letters.index("b"))
# 1
if "f" in letters:
print(letters.index("f"))
5.1.7 count(value) 获取指定数据在列表中出现的次数
count(value) 统计指定元素值在列表中出现的次数
如果给定的元素值在列表中不存在,则返回0
letters =["a", "b", "c", "d", "b"]
print(letters.count("b"))
# 2
print(letters.count("f"))
# 0
5.1.8 sort() 列表数据排序
1、sort() 升序
list.sort() 列表升序排列,不会另存排序结果是直接改变原列表的排序方式
numbers = [3, 51, 2, 8, 6]
numbers.sort()
print(numbers)
# [2, 3, 6, 8, 51]
2、sort(reverse=Ture) 降序
list.sort(reverse=Ture) 列表降序排列,不会另存排序结果是直接改变原列表的排序方式
numbers = [3, 51, 2, 8, 6]
numbers.sort(reverse=True)
print(numbers)
# [51, 8, 6, 3, 2]
3、sorted(list)升序
new_list = sorted(list) 新排序后另存为新的列表,原列表不改变
numbers = [3, 51, 2, 8, 6]
new_numbers = sorted(numbers)
print(new_numbers)
# [2, 3, 6, 8, 51]
print(numbers)
# [3, 51, 2, 8, 6]
4、sorted(list, reverse=Ture)降序
new_list = sorted(list, reverse=Ture) 新排序后另存为新的列表,原列表不改变
numbers = [3, 51, 2, 8, 6]
new_numbers = sorted(numbers, reverse=True)
print(new_numbers)
# [51, 8, 6, 3, 2]
print(numbers)
# [3, 51, 2, 8, 6]
5、 lambda方法
items = [
("prodct1", 10),
("prodct2", 9),
("prodct3", 12)
]
items.sort()
print(items)
# [('prodct1', 10), ('prodct2', 9), ('prodct3', 12)]
# 列表内元素是元组,无法排序
# 自定义排序方法
def sort_item(item):
return item[1]
# 返回商品的价格
items.sort(key=sort_item)
# 按照商品的价格进行升序
print(items)
# [('prodct2', 9), ('prodct1', 10), ('prodct3', 12)]
key=lambda parameters:expression
# items.sort(key=lambda parameters:expression)
items.sort(key=lambda item:item[1])so
items = [
("prodct1", 10),
("prodct2", 9),
("prodct3", 12)
]
# 可以使用lambda表达式 替换上面定义的sort_item方法,可读性会更好
# items.sort(key=lambda parameters:expression)
items.sort(key=lambda item:item[1])
print(items)
# [('prodct2', 9), ('prodct1', 10), ('prodct3', 12)]
5.1.9 列表遍历
1、while循环遍历
2、for 循环遍历
5.1.10 map()映射列表数据
prices = list(map(lambda item: item[1], items))
# map的语义表达式为:item[1] for item in items
items = [
("prodct1", 10),
("prodct2", 9),
("prodct3", 12)
]
prices = []
for item in items:
prices.append(item[1])
print(prices)
# [10, 9, 12]
# 使用map方法简单实现上述功能
prices = list(map(lambda item: item[1], items))
# map的语义表达式为:item[1] for item in items
# prices = [item[1] for item in items]
print(prices)
5.1.11 filter() 过滤列表数据
filtered = list(filter(lambda item: item[1] >= 10, items))
# filter方法的语义表达式为:item for item in items if item[1]>=10
items = [
("prodct1", 10),
("prodct2", 9),
("prodct3", 12)
]
filtered = list(filter(lambda item: item[1] >= 10, items))
# filter方法的语义表达式为:item for item in items if item[1]>=10
# filtered = [item for item in items if item[1]>=10]
print(filtered)
# [('prodct1', 10), ('prodct3', 12)]
5.1.12 zip()组合多个列表
list1 = [1, 2, 3, 4]
list2 = [10, 20, 30]
combine = list(zip("abcd", list1, list2))
print(combine)
# 组合后的元素式元组形式,元素个数和长度最短的那个一致
# [('a', 1, 10), ('b', 2, 20), ('c', 3, 30)]
5.1.13 扩展
1、堆栈
套娃式网站点击跳转,点击返回按钮回到上一个网站,直到回到第一个页面不能继续返回
堆栈:后进先出,python中的堆栈实现逻辑
browsing_session = []
browsing_session.append(1)
browsing_session.append(2)
browsing_session.append(3)
print(browsing_session)
while browsing_session:
last = browsing_session.pop()
if not browsing_session:
print("已经回到初始页面了")
else:
now = browsing_session[-1]
print(f"从{last}回到{now}")
2、队列
队列:先进先出,类似商店排队
前面的移出后 后面的需要移动一个位置,使用deque里的popleft()方法可以便捷操作
from collections import deque
queue = deque([])
queue.append(1)
queue.append(2)
queue.append(3)
print(queue)
# deque([1, 2, 3])
while queue:
last = queue.popleft()
print(last)
if not queue:
print("队列空了")
5.2 tuple 元组
5.2.1 元组的定义
# 标准元组定义方法
point = (1, 2)
print(type(point))
# <class 'tuple'>
# 下面这种也可以,但是最好别这么写
point = 1, 2
print(type(point))
# <class 'tuple'>
# 定义一个空元组
point = ()
# 定义一个至于一个元素的元组,注意逗号不能少
point = (1,)
# 或者
point = 1,
使用tuple()进行数据类型转换:
point = tuple("hello")
print(point)
# ('h', 'e', 'l', 'l', 'o')
point = tuple([1, 2])
print(point)
# (1, 2)
5.2.2 元组合并
point = (1, 2) + (3, 4)
print(point)
# (1, 2, 3, 4)
point = (1, 2) * 3
print(point)
# (1, 2, 1, 2, 1, 2)
元组不允许修改内部元素。
# 获取元组内指定下标的元素
point = (1, 2, 3)
print(point[1])
# 元组的切片操作
point = tuple(range(20))
new_point = point[1:10:2]
print(new_point)
# (1, 3, 5, 7, 9)
print(point)
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
# 把元组内元素赋值给变量
point = tuple(range(10))
first, *other, last = point
print(f"first = {first} other = {other} last {last}")
# first = 0 other = [1, 2, 3, 4, 5, 6, 7, 8] last 9
元组的一个应用场景:两值互换
# 实现2值互换
x = 10
y = 11
x, y = y, x
print(f"x = {x} y = {y}")
补充:
python中array()也可以用来定义一个列表,但是在使用这个函数时需要指定列表内的元素的数据类型,即这个列表内以后只能存储这种类型的数据,插入或者修改为其他数据类型时就会报错,所以一般情况不会使用array()来定义列表,除非有特定的需求。
array — Efficient arrays of numeric values — Python 3.11.4 documentation
from array import array
numbers = array("i", [1, 2, 3])
numbers.insert(2, "b")
# 会报错
# Traceback (most recent call last):
# File "test.py", line 353, in <module>
# numbers.insert(2, "b")
# TypeError: an integer is required (got type str)
5.3 集合
集合:内部元素没有重复,集合内部数据是无序的所以不能通过下标来获取元素值,支持修改。
numbers = [1, 2, 3, 3, 4]
uniques = set(numbers)
print(uniques)
# {1, 2, 3, 4}
5.3.1 集合定义
my_set = set() # 定义一个空集合
set1 = {1, 2}
5.3.2 add(value) 添加元素
set.add(value)
set1 = {1, 2, 3, 4, "hello"}
set1.add(9)
print(set1) # {1, 2, 3, 4, 9, 'hello'}
5.3.3 删除元素
set.remove(value) 没有返回值
set.pop(value) 返回值是被删除的那个元素
set1 = {1, 2, 3, 4, "hello"}
# 使用remove 删除集合中指定元素
temp = set1.remove(2)
print(temp) # None
print(set1) # {1, 3, 4, 'hello'}
# 使用pop 删除集合中随机一个元素
temp1 = set1.pop()
print(temp1) # 1
print(set1) # {3, 4, 'hello'}
5.3.4 len(set) 获取集合长度
set1 = {1, 2, 3, 4, "hello"}
l = len(set1)
print(l) # 5
5.3.5 clear() 清空集合
set.lear()
set1 = {1, 2, 3, 4, "hello"}
set1.clear()
print(set1) # set()
5.3.6 获取多个集合的并集
原集合内容不变,生成一个新的集合
set1 = {1, 2, 3, 4}
set2 = {1, 3, 5, 7}
set3 = set1 | set2
print(set3) # {1, 2, 3, 4, 5, 7}
set4 = set1.union(set2)
print(set4) # {1, 2, 3, 4, 5, 7}
print(set1) # {1, 2, 3, 4}
print(set2) # {1, 3, 5, 7}
5.3.7 获取多个集合的交集
first = {1, 2, 3, 4}
second = {1, 3, 5, 7}
third = first & second
print(third)
# {1, 3}
5.3.8 获取集合的差集
语法:
集合1有 但是集合2没有的元素
集合1 - 集合2
或者 集合1.difference(集合2)
set1 = {1, 2, 3}
set2 = {1, 5, 6}
set3 = set1.difference(set2)
print(set3) # {2, 3}
set4 = set1 - set2
print(set4) # {2, 3}
print(set1) # {1, 2, 3}
print(set2) # {1, 5, 6}
5.3.9 获取多个集合的对称性差异
first = {1, 2, 3, 4}
second = {1, 3, 5, 7}
third = first ^ second
print(third)
# {2, 4, 5, 7}
# 获取first有 但是second没有的元素,和second有但是first没有的元素
# 也就是交集以外的元素
5.3.10 集合内部数据的无序性
集合内部元素不支持使用索引进行数据获取
first = {1, 2, 3, 4}
print(first[0])
# 会报错 TypeError: 'set' object is not subscriptable
5.3.11 集合遍历
集合是无序的,不支持索引,所以不能用while遍历集合
可以用for遍历集合
5.4 dictionary 字典
5.4.1 定义字典
字典的key和value可以是任意数据类型(key不能是字典)
# 定义一个空字典
my_dict = {}
dict1 = dict()
# 定义字典
point = {"x": 1, "y": 2}
# 使用dict()方法定义字典
point = dict(x=1, y=2)
5.4.2 添加元素
stu_score = {}
stu_score["01"] = "xiaoming"
stu_score["02"] = "lili"
print(stu_score) # {'01': 'xiaoming', '02': 'lili'}
5.4.3 修改元素
stu_score = {'01': 'xiaoming', '02': 'lili'}
stu_score["02"] = "xiaoliang"
print(stu_score) # {'01': 'xiaoming', '02': 'xiaoliang'}
5.4.4 获取指定key的value
stu_score = {}
stu_score["01"] = "xiaoming"
stu_score["02"] = "lili"
print(stu_score) # {'01': 'xiaoming', '02': 'lili'}
# 获取字典内某个key对应的value,为了避免因为key不存在,需要先进行判断
if key in stu_score :
print(stu_score [key])
point = {"x":1, "y":2}
# 如果有另外一种取值逻辑:如果key为"a"存在,则获取对应的value,
# 如果不存在key为"a",则获取某个指定的默认值(比如0)
print(point.get("a", 0))
5.4.5 删除指定元素
删除字典元素的方式:
dict.pop(key)
del dict[key]
stu_score = {'01': 'xiaoming', '02': 'xiaoliang', '03': 'xiaohong'}
temp = stu_score.pop("01")
print(temp) # xiaoming
print(stu_score) # {'02': 'xiaoliang', '03': 'xiaohong'}
del stu_score['02']
print(stu_score) # {'03': 'xiaohong'}
5.4.6 清空字典
dict.clear()
stu_score = {'01': 'xiaoming', '02': 'xiaoliang', '03': 'xiaohong'}
stu_score.clear()
print(stu_score) # {}
5.4.7 获取字典全部key
dict.keys()
stu_score = {'01': 'xiaoming', '02': 'xiaoliang', '03': 'xiaohong'}
keys = stu_score.keys()
print(type(keys)) # <class 'dict_keys'>
print(keys) # dict_keys(['01', '02', '03'])
5.4.8 获取字典的元素
dict.items()
stu_score = {'01': 'xiaoming', '02': 'xiaoliang', '03': 'xiaohong'}
element = stu_score.items()
print(type(element)) # <class 'dict_items'>
print(element) # dict_items([('01', 'xiaoming'), ('02', 'xiaoliang'), ('03', 'xiaohong')])
5.4.9 字典应用于循环
# 字典用于循环
for key in point:
print(key, point[key])
# x 1
# y 2
for key, value in point.items():
print(key, value)
# x 1
# y 2
for x in point.items():
print(x)
# ('x', 1)
# ('y', 2)
5类数据容器对比:
5.5 生成器对象
values = {}
for x in range(5):
values[x] = x * 2
print(f"dict: {values}")
# dict: {0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
# 上面的语句等价于
values = {x: x * 2 for x in range(5)}
print(f"dict: {values}")
# dict: {0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
values = [x * 2 for x in range(5)]
print(f"list: {values}")
# list: [0, 2, 4, 6, 8]
values = (x * 2 for x in range(5))
print(f"tuple: {values}")
# tuple: <generator object <genexpr> at 0x01656808>
# 得到的是一个可迭代的对象————》 生成器对象
生成器对象的作用??
from sys import getsizeof
values = [x * 2 for x in range(100)]
print("list: ", getsizeof(values))
# list: 452
values = (x * 2 for x in range(100))
print("gen: ", getsizeof(values))
# gen: 56
values = [x * 2 for x in range(1000000)]
print("list: ", getsizeof(values))
# 看下内存占用情况
# list: 4348728
values = (x * 2 for x in range(1000000))
print("gen: ", getsizeof(values))
# 看下内存占用情况
# gen: 56
# 可以看出使用迭代器,随着处理的数据量急剧增大,每次迭代时占用的内存没有变化
所以在处理大数据集或者可能是一个无限的数据流的情况时,使用生成器表达式得到一个生成器,把每次处理的数据量存入内存,会比把全部数据存入内存,数据处理速度快很多。
但是注意在迭代过程中,无法获取处理数据的总数,因为内存存储的是部分数据:
values = (x * 2 for x in range(1000000))
print("gen: ", getsizeof(values))
# 看下内存占用情况
# gen: 56
print(len(values))
# 报错: TypeError: object of type 'generator' has no len()
5.6 解包操作
5.6.1 多个列表合并
numbers = [1, 2, 3]
print(numbers)
# 打印的是一个列表 [1, 2, 3]
print(*numbers)
# 打印的是列表内的数据 1 2 3
values = list(range(5))
print(values)
# [0, 1, 2, 3, 4]
# 多个数据类型转换为列表,再直接合并
values = [*range(5), *"hello"]
print(values)
# [0, 1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o']
first = [1, 2]
second = [3, 4]
values = [*first, *"world", *second, *"hello"]
print(values)
# [1, 2, 'w', 'o', 'r', 'l', 'd', 3, 4, 'h', 'e', 'l', 'l', 'o']
5.6.2 多个字典合并
first = {"x": 1}
second = {"x": 10, "y": 20}
combined = {**first, **second, "z": 30}
print(combined)
# {'x': 10, 'y': 20, 'z': 30}
# 多个字典合并时,如果出现key值相同的情况,会取最后那个对应的value
5.7 字符串
上面第二部分已经介绍过
5.8 练习
获取文本中出现次数最多的字符
str = "fddhbfegrkthwbcndvgpoirnjbugrnmbqplfekvjmfi jfcdrgvfcydsnvj b "
# 去除文本内部空格
str.strip()
list = list(str)
char_num = {}
for char in list:
if char in char_num:
char_num[char] += 1
else:
char_num[char] = 1
count = 0
value = ""
for char, num in char_num.items():
if num > count:
count = num
value = char
print(f"字符{value}出现次数最多, 出现了{count}次")
str = "fddhbfegrkthwbcndvgpoirnjbugrnmbqplfekvjmfi jfcdrgvfcydsnvj b "
# 去除文本内部空格
str.strip()
list = list(str)
char_num = {}
for char in list:
if char in char_num:
char_num[char] += 1
else:
char_num[char] = 1
# print(char_num)
print(type(char_num.items()))
# <class 'dict_items'>
print(type(sorted(char_num.items())))
# <class 'list'>
char_num_sorted = sorted(char_num.items(), key=lambda kv: kv[1], reverse=True)
print(char_num_sorted[0])
六、文件操作
6.1 文件读取
6.1.1 open() 打开文件
文件夹之间用斜线隔开。在 Windows 中使用倒斜杠\来分隔,在 Mac OS 和 Linux 中使 用正斜杠/作为路径分隔符
文件路径可以是相对路径也可以是绝对路径
print("==================================")
# 文件夹之间用斜线隔开。在 Windows 中使用倒斜杠\来分隔,在 Mac OS 和 Linux 中使 用正斜杠/作为路径分隔符
# 文件路径可以是相对路径也可以是绝对路径
f = open("ecommerce\shopping\sales.py", "r", encoding="UTF-8")
print(type(f)) # <class '_io.TextIOWrapper'>
6.1.2 read()读取文件内容
f = open("../../test.txt", "r", encoding="UTF-8")
print(type(f)) # <class '_io.TextIOWrapper'>
content = f.read(10)
print(type(content)) # <class 'str'>
print(content) # gfdskjhfrk
6.1.3 readlines()读取文件
可以看到使用f.read(10)读了10个字节,之后再使用f.readlines()读取剩余全部内容,并按行存入列表中。读文件时是有一个类似指针的东西,标记当前读取的进度,只要不关闭文件或者重新把文件指针放在文件开头,下次读取时就会从上次读取结束的位置开始读数据。
f = open("../../test.txt", "r", encoding="UTF-8")
print(type(f)) # <class '_io.TextIOWrapper'>
content = f.read(10)
print(type(content)) # <class 'str'>
print(content) # gfdskjhfrk
content1 =f.readlines()
print(type(content1)) # <class 'list'>
print(content1) # ['lgjnjlbdfifghrughbnt\n', 'sgdfbifjrn vfgdb ujhuegyrg\n', 'hfcidufgv dvheuigfrrgfbh\n']
6.1.4 readline()读取文件
f = open("../../test.txt", "r", encoding="UTF-8")
print(type(f)) # <class '_io.TextIOWrapper'>
content = f.readline()
print(type(content)) # <class 'str'>
print(content) # gfdskjhfrklgjnjlbdfifghrughbnt
content2 = f.readline() # sgdfbifjrn vfgdb ujhuegyrg
6.1.5 使用for循环读取文件
f = open("../../test.txt", "r", encoding="UTF-8")
print(type(f)) # <class '_io.TextIOWrapper'>
for line in f:
print(line)
"""
gfdskjhfrklgjnjlbdfifghrughbnt
sgdfbifjrn vfgdb ujhuegyrg
hfcidufgv dvheuigfrrgfbh
"""
6.1.6 关闭文件连接
不关闭文件连接,文件就会被一直占用,也就不能对文件进行其他操作。
6.1.7 使用with open打开文件
with open("../../test.txt", "r", encoding="utf-8") as f:
print(f.readlines())
# ['gfdskjhfrklgjnjlbdfifghrughbnt\n', 'sgdfbifjrn vfgdb ujhuegyrg\n', 'hfcidufgv dvheuigfrrgfbh\n']
6.2 文件写入
如果不使用flush()把缓冲区的内容刷入磁盘,只要再文件操作完毕后使用close()也是可以保存内容到磁盘的,因为close()内置了flush()功能
练习:
账单文件bill.txt 内容如下:
需求:读取文件,把文件备份到bill.txt.bak,同时把标记为测试的数据丢弃
正则匹配
Python正则表达式是一种强大的文本处理工具(也就是处理字符串 ),可以用来匹配、搜索、替换文本中的特定模式。下面是Python正则表达式的用法详解:
1. 匹配单个字符
. 匹配任意一个字符,除了换行符
[] 匹配括号中任意一个字符
[^] 匹配不在括号中的任意一个字符
\d 匹配任意一个数字
\D 匹配任意一个非数字字符
\w 匹配任意一个字母、数字或下划线
\W 匹配任意一个非字母、数字或下划线字符
\s 匹配任意一个空白字符
\S 匹配任意一个非空白字符:
import re
# 匹配任意一个字符
pattern = r'.'
text = 'hello world'
result = re.findall(pattern, text)
print(result) # ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
# 匹配数字
pattern = r'\d'
text = 'abc123def456'
result = re.findall(pattern, text)
print(result) # ['1', '2', '3', '4', '5', '6']
# 匹配非数字字符
pattern = r'\D'
text = 'abc123def456'
result = re.findall(pattern, text)
print(result) # ['a', 'b', 'c', 'd', 'e', 'f']
# 匹配字母、数字或下划线
pattern = r'\w'
text = 'hello_world123'
result = re.findall(pattern, text)
print(result) # ['h', 'e', 'l', 'l', 'o', '_', 'w', 'o', 'r', 'l', 'd', '1', '2', '3']
# 匹配非字母、数字或下划线字符
pattern = r'\W'
text = 'hello_world123'
result = re.findall(pattern, text)
print(result) # []
# 匹配空白字符
pattern = r'\s'
text = 'hello world'
result = re.findall(pattern, text)
print(result) # [' ']
# 匹配非空白字符
pattern = r'\S'
text = 'hello world'
result = re.findall(pattern, text)
print(result) # ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
2. 匹配多个字符
* 匹配前面的字符0次或多次
+ 匹配前面的字符1次或多次
? 匹配前面的字符0次或1次
{n} 匹配前面的字符恰好n次
{n,} 匹配前面的字符至少n次
{n,m} 匹配前面的字符至少n次,但不超过m次
例如:
import re
# 匹配前面的字符0次或多次
pattern = r'ab*'
text = 'a ab abb abbb abbbb'
result = re.findall(pattern, text)
print(result) # ['a', 'ab', 'abb', 'abbb', 'abbb']
# 匹配前面的字符1次或多次
pattern = r'ab+'
text = 'a ab abb abbb abbbb'
result = re.findall(pattern, text)
print(result) # ['ab', 'abb', 'abbb', 'abbb']
# 匹配前面的字符0次或1次
pattern = r'ab?'
text = 'a ab abb abbb abbbb'
result = re.findall(pattern, text)
print(result) # ['a', 'ab', 'ab', 'ab', 'ab']
# 匹配前面的字符恰好n次
pattern = r'ab{2}'
text = 'a ab abb abbb abbbb'
result = re.findall(pattern, text)
print(result) # ['abb']
# 匹配前面的字符至少n次
pattern = r'ab{2,}'
text = 'a ab abb abbb abbbb'
result = re.findall(pattern, text)
print(result) # ['abb', 'abbb', 'abbb']
# 匹配前面的字符至少n次,但不超过m次
pattern = r'ab{2,3}'
text = 'a ab abb abbb abbbb'
result = re.findall(pattern, text)
print(result) # ['abb', 'abbb', 'abbb']
3. 匹配开头和结尾
^ 匹配字符串的开头
$ 匹配字符串的结尾
例如:
import re
# 匹配字符串的开头
pattern = r'^hello'
text = 'hello world'
result = re.findall(pattern, text)
print(result) # ['hello']
# 匹配字符串的结尾
pattern = r'world$'
text = 'hello world'
result = re.findall(pattern, text)
print(result) # ['world']
4. 匹配分组
() 将括号中的内容作为一个分组
| 匹配多个模式中的任意一个
例如:
import re
# 将括号中的内容作为一个分组
pattern = r'(hello) (world)'
text = 'hello world'
result = re.findall(pattern, text)
print(result) # [('hello', 'world')]
# 匹配多个模式中的任意一个
pattern = r'hello|world'
text = 'hello world'
result = re.findall(pattern, text)
print(result) # ['hello', 'world']
5. 匹配转义字符
\ 转义字符
例如:
import re
# 匹配转义字符
pattern = r'\$'
text = 'The price is $10.'
result = re.findall(pattern, text)
print(result) # ['$']
七、异常exceptions
7.1 捕获异常
捕获全部异常:
方式一:
try:
可能发生错误的代码
except:
如果发生异常就执行这里的代码
方式二:
try:
可能发生错误的代码
except Exception as er:
如果发生错误执行这里的代码
age = int(input("age: "))
# ValueError: invalid literal for int() with base 10: 'e'
# 数据异常情况需要提前捕获并设计处理逻辑,避免程序崩溃
try:
age = int(input("age: "))
except ValueError as er:
# 如果try模块内语句有相应的ValueError报错,就会执行except模块里的逻辑
# 一般需要把报错信息和类型打印出来,所以先给异常取一个别名er
print("输入的年龄不正确,请重新输入")
print(er)
# invalid literal for int() with base 10: 'a'
print(type(er))
# <class 'ValueError'>
else:
# 如果try模块里没有代码报错就会执行else里面的语句
print("没有代码报错")
7.2 捕获多个异常
try:
age = int(input("age: "))
xfactor = 10 / age
except ValueError as er:
print("输入的年龄不正确,请重新输入")
print(er)
print(type(er))
except ZeroDivisionError as zero:
print("输入的年龄不正确,请重新输入")
print(zero)
print(type(zero))
else:
# 如果try模块里没有代码报错就会执行else里面的语句
print("没有代码报错")
如果我们希望可以一次捕获多个异常,并且抛出具有概括性的提示文案
try:
age = int(input("age: "))
xfactor = 10 / age
except (ValueError, ZeroDivisionError) as er:
print("输入的年龄不正确,请重新输入")
else:
# 如果try模块里没有代码报错就会执行else里面的语句
print("没有代码报错")
7.3 异常的else和finally语句
在代码中会用到外部资源,如文件、网络连接、数据库连接等,使用完要记得释放资源,可以把资源释放的语句放在finally语句里面。
7.3.1 在try模块连接资源在finally模块关闭资源
try:
file = open("test.py")
age = int(input("age: "))
xfactor = 10 / age
except (ValueError, ZeroDivisionError):
# try模块内有except中指定的异常时就会执行except模块,捕获异常
print("输入的年龄不正确,请重新输入")
else:
# try模块里没有代码报错就会执行else里面的语句
print("没有代码报错")
finally:
# 在finally模块内关闭所有资源的连接,释放资源
# 不管try模块是否有异常,finally模块总会执行
file.close()
7.3.2 使用with语句自动释放资源
with语句后面可以打开多个资源,并且在代码执行完后会自动释放这些资源。
try:
# 使用with语句可以打开多个资源
with open("test.py") as file, open("app.py") as target:
print("test.py opened")
print("app.py opened")
age = int(input("age: "))
xfactor = 10 / age
except (ValueError, ZeroDivisionError):
# try模块内有except中指定的异常时就会执行except模块,捕获异常并抛出
print("输入的年龄不正确,请重新输入")
else:
# try模块里没有代码报错就会执行else里面的语句
print("没有代码报错")
7.4 异常具有传递性
7.5 抛出异常
可以在编写自己的函数时抛出异常,但是不推荐这么做,代价比较大。
raise 异常类型("这里给出一个异常提示信息")
如:
raise ValueError("error 细节描述")
def calculate_xfactor(age):
if age <= 0:
raise ValueError("这里是你定制的异常提示信息")
return 10 / age
try:
x = int(input("年龄:"))
calculate_xfactor(x)
except ValueError as error:
print(error)
python的内置异常有哪些??Built-in Exceptions — Python 3.11.4 documentation
from timeit import timeit
# timeit 可以用来计算执行时间
code1 = """
def calculate_xfactor(age):
if age <= 0:
raise ValueError("这里是你定制的异常提示信息")
return 10 / age
try:
calculate_xfactor(-1)
except ValueError as error:
print(error)
"""
code2 = """
def calculate_xfactor(age):
if age <= 0:
return None
return 10 / age
xfactor = calculate_xfactor(-1)
if xfactor == None:
pass
"""
print("code1= ",timeit(code1, number = 10000))
# 计算code1代码执行10000次使用的时间
# code1= 2.6951908
print("code2= ", timeit(code2, number = 10000))
# code2= 0.0021061000000002217
可以看到在自己函数中抛出&捕获异常,处理时间差距很大,而且不抛异常代码也更简洁。
八、类classes
8.1 类定义
类命名使用驼峰,每个单词首字母大写
每个方法都至少有一个参数——》 self
# 定义类Point
class Point:
# 定义一个类方法
def draw(self):
print("draw")
# 类的实例化
point = Point()
print(type(point))
# <class '__main__.Point'>
print(isinstance(point, Point))
# True
# isinstance()方法判断判断point是不是Point的实例
8.2 构造函数
创建实例时执行构造函数
定义类的方法,每个方法至少包含一个参数self,self是对当前类的实例对象的引用
使用self可以读取当前实例对象的属性,调用这个实例对象的方法
成员方法中使用成员属性(类属性、实例属性)必须通过self
# 定义类Point
class Point:
# 定义类的方法,每个方法至少包含一个参数self,self是对当前类的实例对象的引用
# 使用self可以读取当前实例对象的属性,调用这个实例对象的方法
# 定义构造函数 init前后各有2个下划线
# 构造函数在实例化时执行
# 一个点需要x y坐标来唯一确定
def __init__(self, x, y):
self.x = x
self.y = y
# x y是实例属性
# 定义一个类方法
def draw(self):
print("draw")
# 类的实例化
point = Point(1, 2)
print(type(point))
# <class '__main__.Point'>
print(isinstance(point, Point))
# True
# isinstance()方法判断判断point是不是Point的实例
# 调用类属性
print(point.x)
# 1
# 类实例化后,调用实例对象的方法时,不用传递实例对象point.draw(point)
# 没必要传参,python解释器会替我们把实例化的对象传递进去
# 调用实例对象的方法
point.draw()
# draw
8.3 类和实例属性
8.3.1 实例属性
在类定义中可以创建实例属性,在类实例化后,实例对象也可以定义属于自己的新属性。
每个实例对象的实例属性值可以不同
class Point:
def __init__(self, x, y):
# 定义实例属性x y
self.x = x
self.y = y
def draw(self):
print("draw")
point1 = Point(5, 6)
# 类实例化后,还可以定义实例特有的属性z
point1.z = 7
point2 = Point(3, 7)
8.3.2 类属性
类属性是在类级别定义的属性,所以在所有实例中都是相同的。
可以通过实例对象访问类属性,也可以通过类访问类属性。
class Point:
# 定义类 属性,类的实例共有这个属性
default_color = "red"
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print("draw")
point1 = Point(5, 6)
point2 = Point(3, 7)
# 通过实例对象访问类属性
print(point1.default_color)
# red
print(point2.default_color)
# red
# 通过类访问类属性
print(Point.default_color)
# red
修改类属性的值:
1)通过类修改类属性,那么之后对类属性的访问,不管是实例对象访问还是类访问,该属性值都是最新的
class Point:
default_color = "red"
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print("draw")
# 在访问类属性之前对类属性进行修改,之后访问类属性获得的就是最新的值
# 通过类名.类属性 = 新值 重新赋值
Point.default_color = "yellow"
point1 = Point(5, 6)
point2 = Point(3, 7)
# 通过实例对象访问类属性
print(point1.default_color)
# yellow
print(point2.default_color)
# yellow
# 通过类访问类属性
print(Point.default_color)
# yellow
2)通过实例对象修改类属性的值,那么之后类属性访问获得的值,只有这个实例对象获得到最新的值,其他实例对象和类都是获得之前的旧值
class Point:
default_color = "red"
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print("draw")
point1 = Point(5, 6)
point2 = Point(3, 7)
# 通过实例对象修改类属性的值,那么之后类属性访问时,只有这个实例对象可以拿到最新的类属性值,其他的实例对象和类访问到的是旧的类属性值
point1.default_color = "green"
# 通过实例对象访问类属性
print(point1.default_color)
# green
print(point2.default_color)
# red
# 通过类访问类属性
print(Point.default_color)
# red
一般情况我们使用实例属性比较多,类属性只有在所有实例对象都共有某个属性值时才会定义,并且一般情况不会修改类属性的值。
8.4 类和实例方法
8.4.1 实例方法
class Point:
default_color = "red"
# 定义实例方法
# 实例方法__init__在实例创建的时候调用
def __init__(self, x, y):
self.x = x
self.y = y
# 实例方法draw
def draw(self):
print("draw")
# 调用实例方法
point1 = Point(3, 8)
point2 = Point(5, 3)
point1.draw()
point2.draw()
8.4.2 类方法
为什么要定义类方法呢??
在创建实例对象时需要调用__init__方法初始化一些参数,如果某些特殊实例对象 在初始化时需要传递一些特殊的参数,但是又不是所有实例对象都需要传递这些特殊参数。这样的话在创建这些特殊实例对象时就需要重复传递这些参数,为了使代码简化,可以定义 工厂方法 来产出这些参数,这样你在创建特殊实例对象时只需要调用这些工厂方法就行了。
类方法的第一个参数设置为cls,也就是class的简写,这个方法是供类调用的
在类方法定义前面需要加一个类装饰器 @classmethod
举个例子:
class Point:
# 定义实例方法
# 实例方法的第一个参数设置为self,指代的是实例对象本身,也就是这方法是供实例对象调用的
def __init__(self, x, y):
self.x = x
self.y = y
# 定义类方法
# 类方法的第一个参数设置为cls,也就是class的简写,这个方法是工类调用的
# 在类方法定义前面需要加一个类装饰器 @classmethod
@classmethod
def zero(cls):
return cls(0, 0)
def draw(self):
print("draw")
# 有一些特殊需求,需要创建多个零点实例对象
# 可以使用普通的类实例化方法创建这些实例对象
point1 = Point(0, 0)
point2 = Point(0, 0)
point3 = Point(0, 0)
# 但是调用工厂方法更简单 代码也更好看
point4 = Point.zero()
point4.draw()
8.5 magic methods魔术方法
方法名前后有2个下划线的方法,由python解释器自动调用
参考:A Guide to Python's Magic Methods « rafekettler.com
下面介绍几个类里面的magic method
8.5.1 __str__
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print(f"draw ({self.x}, {self.y})")
point = Point(3, 4)
print(point)
# <__main__.Point object at 0x018AF430> 是一个对象地址
# 但是我们想要打印的是点对象的坐标(3, 4)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# 定义__str__方法就可以得到点对象字符串
def __str__(self):
return f"({self.x}, {self.y})"
def draw(self):
print(f"draw ({self.x}, {self.y})")
point = Point(3, 4)
print(point)
# (3, 4)
8.5.2 比较对象大小的魔法方法
比较的是2个对象的内存地址,2个对象的地址不一样 所以是False
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print(f"draw ({self.x}, {self.y})")
point = Point(3, 4)
point1 = Point(3, 4)
print(point == point1)
# False
# 比较的是2个对象的内存地址,2个对象的地址不一样 所以是False
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
point1 = Point(1, 2)
point2 = Point(1, 2)
# 这个时候比较 point1 == point2 就可以了
print(point1 == point2)
# True
print(point1 > point2)
# TypeError: '>' not supported between instances of 'Point' and 'Point'
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __gt__(self, other):
return self.x > other.x and self.y > other.y
point1 = Point(1, 2)
point = Point(10, 20)
print(point > point1)
# True
print(point < point1)
# False
# 不用再去定义__lt__方法就可以实现> < 的比较
8.5.3 对象进行算术运算的魔法方法
# 统计标签出现的次数
class TagCloud:
def __init__(self):
# 定义一个字典存储标签和对应次数
self.tags = {}
# 添加标签
def add(self, tag):
# self.tags.get(tag, 0)获取字典内key为tag的value,如果没有对应的key则添加,并给默认value为0
# tag名称不区分大小写,统一转换为小写
self.tags[tag.lower()] = self.tags.get(tag.lower(), 0) + 1
cloud = TagCloud()
cloud.add("Python")
cloud.add("sql")
cloud.add("python")
print(cloud.tags)
# {'python': 2, 'sql': 1}
8.5.4 自定义的magic method
# 统计标签出现的次数
class TagCloud:
def __init__(self):
# 定义一个字典存储标签和对应次数
self.tags = {}
# 添加标签
def add(self, tag):
# self.tags.get(tag, 0)获取字典内key为tag的value,如果没有对应的key则添加,并给默认value为0
self.tags[tag.lower()] = self.tags.get(tag.lower(), 0) + 1
# 获取字典对象中指定key的value
def __getitem__(self, tag):
return self.tags.get(tag.lower(), 0)
cloud = TagCloud()
cloud.add("Python")
cloud.add("sql")
cloud.add("python")
print(cloud.tags)
# {'python': 2, 'sql': 1}
# 获取标签为Java出现的次数
print(cloud["java"])
# 返回0
print(cloud["python"])
# 返回2
# 统计标签出现的次数
class TagCloud:
def __init__(self):
# 定义一个字典存储标签和对应次数
self.tags = {}
# 添加标签
def add(self, tag):
# self.tags.get(tag, 0)获取字典内key为tag的value,如果没有对应的key则添加,并给默认value为0
self.tags[tag.lower()] = self.tags.get(tag.lower(), 0) + 1
# 插入键值对 或者修改指定key的value
def __setitem__(self, tag, count):
self.tags[tag.lower()] = count
cloud = TagCloud()
cloud.add("Python")
cloud.add("sql")
cloud.add("python")
print(cloud.tags)
# {'python': 2, 'sql': 1}
cloud.tags["java"] = 5
print(cloud.tags)
# {'python': 2, 'sql': 1, 'java': 5}
# 统计标签出现的次数
class TagCloud:
def __init__(self):
# 定义一个字典存储标签和对应次数
self.tags = {}
# 添加标签
def add(self, tag):
# self.tags.get(tag, 0)获取字典内key为tag的value,如果没有对应的key则添加,并给默认value为0
self.tags[tag.lower()] = self.tags.get(tag.lower(), 0) + 1
# 获取字典对象中指定key的value
def __getitem__(self, tag):
return self.tags.get(tag.lower(), 0)
# 插入键值对 或者修改指定key的value
def __setitem__(self, tag, count):
self.tags[tag.lower()] = count
# 获取字典长度
def __len__(self):
return len(self.tags)
def __iter__(self):
# 使用内置方法iter获取一个迭代器对象,迭代器对象是遍历容器的对象,一次获取一个元素
return iter(self.tags)
cloud = TagCloud()
cloud.add("Python")
cloud.add("sql")
cloud.add("python")
print(cloud.tags)
# {'python': 2, 'sql': 1}
print(len(cloud.tags))
# 3
for tag, count in cloud.tags.items():
print(f"tag= {tag}, count= {count}")
# tag= python, count= 2
# tag= sql, count= 1
# tag= java, count= 5
for tag, count in iter(cloud.tags.items()):
print(f"tag= {tag}, count= {count}")
# tag= python, count= 2
# tag= sql, count= 1
# tag= java, count= 5
8.6 python的私有成员
在属性名前面加上2个下划线__ (快速修改:选中属性名 点击F2修改后回车即可全局修改)
实例对象不能直接访问私有属性,会报错:
实例对象.__tags 就会报错AttributeError: 'TagCloud' object has no attribute '__tags'
可以通过实例对象.__dict__ 获取一个字典,字典内部是这个类包含的全部属性,所以还是可以访问到这个私有属性的。
# 统计标签出现的次数
class TagCloud:
def __init__(self):
# 定义一个字典存储标签和对应次数
self.__tags = {}
# 添加标签
def add(self, tag):
# self.tags.get(tag, 0)获取字典内key为tag的value,如果没有对应的key则添加,并给默认value为0
self.__tags[tag.lower()] = self.__tags.get(tag.lower(), 0) + 1
# 获取字典对象中指定key的value
def __getitem__(self, tag):
return self.__tags.get(tag.lower(), 0)
# 插入键值对 或者修改指定key的value
def __setitem__(self, tag, count):
self.__tags[tag.lower()] = count
cloud = TagCloud()
cloud.add("Python")
cloud.add("sql")
cloud.add("python")
# print(cloud.__tags)
# 可以看到从外部可以访问实例对象的属性tags,我们需要设置属性为私有,避免从外部访问
# 怎么把属性设置为私有呢?? 在属性名前面加上2个下划线__ 选中属性名 点击F2修改后回车即可全部修改
# 再次执行代码 只要访问到了私有属性:cloud.__tags 就会报错AttributeError: 'TagCloud' object has no attribute '__tags'
# 但是把属性设置私有并不能完全避免从外部访问它,还是由其他方法能够访问到私有属性
# cloud.__dict__ 可以获取到一个字典,字典内部是这个类包含的全部属性
print(cloud.__dict__) # {'_TagCloud__tags': {'python': 2, 'sql': 1}}
print(cloud._TagCloud__tags) # {'python': 2, 'sql': 1}
print(cloud._TagCloud__tags["python"]) # 2
# 使用上面的方法还是可以访问到类的私有属性
# 所以虽然python能够设置私有属性, 但是它并没有真正意义的私有
8.7 类属性property
8.7.1 使用property()方法创建类属性
class Product:
def __init__(self, price):
self.price = price
product = Product(-50)
# 显然上面的代码没有考虑属性的取值
代码优化方案一:
class Product:
def __init__(self, price):
# self.price =price
# self.__price = price
self.set_price(price)
def get_price(self):
return self.__price
def set_price(self, value):
if value < 0:
raise ValueError("价格不允许为负数")
self.__price = value
product = Product(-50)
可以抛出异常
Traceback (most recent call last):
File "test.py", line 799, in <module>
product = Product(-50)
File "test.py", line 789, in __init__
self.set_price(price)
File "test.py", line 796, in set_price
raise ValueError("价格不允许为负数")
File "test.py", line 799, in <module>
product = Product(-50)
File "test.py", line 789, in __init__
self.set_price(price)
File "test.py", line 796, in set_price
raise ValueError("价格不允许为负数")
ValueError: 价格不允许为负数
处理方案二:
类属性————property
实例对象属性————attribute
# 内置类属性函数 property(fget, fset, fdel, doc) 返回一个类属性对象,这个类属性对象会获取 实例对象的属性值
# 参数fget是获取 实例对象属性attribute 的方法名
# 参数fset是设置 实例对象属性 的方法名
# 参数fdel是删除 实例对象属性 的方法名
# 参数doc是说明文档
注意这里传参只是方法名,是fget 不是fget(),而且并没有调用方法
fget、 fset、fdel这些方法还是需要自己编写的,名称可以自定义
class Product:
def __init__(self, price):
self.set_price(price)
def get_price(self):
return self.__price
def set_price(self, value):
if value < 0:
raise ValueError("价格不允许为负数")
self.__price = value
price = property(get_price, set_price)
# 此处定义的类属性price,实例对象也可以访问
# 传入负数也会抛出异常
# product = Product(-50)
# Traceback (most recent call last):
# File "test.py", line 826, in <module>
# product = Product(-50)
# File "test.py", line 813, in __init__
# self.set_price(price)
# File "test.py", line 820, in set_price
# raise ValueError("价格不允许为负数")
# ValueError: 价格不允许为负数
# 传入正确数值
product = Product(50)
# product.price = -10 也会触发抛出异常,和上面的实例化传参抛出的异常一样
print(product.price)
虽然使用类属性返回了需要的价格,但是我们发现实例对象依然可以调用实例方法set_price()和 get_price() 污染了对象接口,可以把get_price和set_price 改为__get_price 和__set__price变为私有方法
或者在方法定义前添加@classmethod把实例方法 变为 类方法
8.7.2 装饰器@property 创建类属性
使用@property装饰器定义类属性,类属性名就是下面的方法名
class Product:
def __init__(self, value):
self.__jiage = value
# 使用@property装饰器定义类属性,类属性名就是下面的方法名
@property
def price(self):
return self.__jiage
# python解释器看到@property和方法名price 会自动创建 类属性price
# 类属性有2个方法:setter和getter
# 定义装饰器
@price.setter
def price(self, value):
if value < 0:
raise ValueError("价格不能是负数")
self.__jiage = value
# product = Product(-19) # 会抛出异常
product = Product(10)
print(product.price) # 10
# 修改类属性的值
product.price = 20
print(product.price) # 20
如果没有定义类属性的setter方法,则在实例化后就不能进行类属性值的修改:
# 类属性有2个方法:setter和getter
# 定义装饰器
@price.setter
def price(self, value):
if value < 0:
raise ValueError("价格不能是负数")
self.__jiage = value
8.8 继承inheritance
8.8.1 单继承和多层继承
1. 单继承
单继承:子类只继承一个父类
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print("eat")
# 哺乳类动物Mammal 继承 动物Animal的方法和属性
class Mammal(Animal):
def walk(self):
print("walk")
m = Mammal("sheep", 3)
m.eat()
m.walk()
print(m.name)
2. 多层继承
多层继承:继承关系为多层传递,如生活中的爷爷、父亲、儿子
3. isinstance(instance, class)
作用:判断instance 是否是class的实例对象,返回的是True 或者False
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print("eat")
# 哺乳类动物Mammal 继承 动物Animal的方法和属性
class Mammal(Animal):
def walk(self):
print("walk")
m = Mammal("sheep", 3)
print(isinstance(m, Mammal)) # True
print(isinstance(m, Animal)) # True
所有的类都是从object类继承而来的,object是所有类的父类
print(isinstance(m, object)) # True
4. issubclass(sub, base)
作用:判断sub类是不是base类的子类,返回的是True 或者False
print(issubclass(Mammal, Animal)) # True
print(issubclass(Mammal, object)) # True
5. 重写父类方法/属性
在子类中重新定义同名佛如属性或方法即可。
子类重写父类同名方法
- 父类的方法不能满足子类的需要,可以对父类的方法重写,重写父类方法的目的是为了给他扩展功能
- 在子类中定义了一个和父类同名的方法(参数也一样),即为对父类的方法重写
- 子类调用同名方法,默认只会调用子类的
使用第一种方式别忘了方法里面的self
子类调用父类同名方法
- 父类名.同名方法(self, 形参1, ……)
- super(子类名, self).同名方法(形参1, ……)
- super().同名方法(形参1, ……) ————推荐使用这种方式
8.8.2 多继承
所谓多继承,即子类有多个父类,并且具有它们的特征
class 子类名(父类1, 父类2, ……):
pass
1、 多继承--查看子类继承父类的继承顺序
查看子类的继承顺序:子类名.__mro__
# 定义2个类,它们没有继承关系,是平级的
class SmallDog(object):
def eat(self):
print('吃小东西')
# 再定义一个类
class BigDog(object):
def drink(self):
print('大口喝水')
# 定义一个子类,多继承于上面2个父类
class SuperDog(SmallDog, BigDog):
pass
# 查看类的继承顺序
print(SuperDog.__mro__)
运行结果
(<class '__main__.SuperDog'>, <class '__main__.SmallDog'>, <class '__main__.BigDog'>, <cl
2、多继承--调用父类同名方法
默认调用情况
如果继承过来的2个父类的方法同名,默认调用先继承的那个父类的同名方法
子类调用父类同名方法
- 父类名.同名方法(self, 形参1, ……):调用指定的父类的同名方法
- super(类名x, self).同名方法(形参1, ……):调用继承顺序中类名x的下一个类的同名方法
- super().同名方法(形参1, ……):调用先继承的那个父类的同名方法
# 定义2个类,它们没有继承关系,是平级的
class SmallDog(object):
def eat(self):
print('吃小东西')
# 再定义一个类
class BigDog(object):
def eat(self):
print('啃大骨头')
# 定义一个子类,多继承于上面2个父类
class SuperDog(SmallDog, BigDog):
def eat(self):
print('吃蟠桃')
print('='*20)
# 子类调用父类同名方法:
# 1. 父类名.同名方法(self, 形参1, ……)
SmallDog.eat(self) # 调用SmallDog的eat()
print('=' * 20)
# 2. super(类名, self).同名方法(形参1, ……):调用继承顺序中类名的下一个类的同名方法
# 继承顺序中,SmallDog的下一个类是BigDog,所以调用BigDog的eat()
super(SmallDog, self).eat()
print('=' * 20)
# 3. super().同名方法(形参1, ……) :调用先继承父类的同名方法
# 所以调用的是SmallDog的eat()方法
super().eat()
# 定义子类对象,调用方法
sd = SuperDog()
sd.eat()
运行结果:
吃蟠桃
====================
吃小东西
====================
啃大骨头
====================
吃小东西
8.8.3 私有和继承
父类中的 私有方法和私有属性 子类 不能继承
如果父类的公有方法中有调用父类的私有方法和私有属性,那么子类可以通过调用父类公有方法 间接的访问父类的私有方法、私有属性。
# 定义一个父类, Animal
class Animal(object):
# 添加一个type属性
def __init__(self):
self.__type = '动物' # 私有
def __leave(self): # 私有
print('休产假3个月')
# 通过公有方法,间接访问私有元素
def use_private(self):
print(self.__type)
self.__leave()
# 定义一个子类
class Dog(Animal):
def test(self):
# print(self.__type) # err,私有不能直接继承使用
# self.__leave() # err,私有不能直接继承使用
pass
# 创建子类对象
dog1 = Dog()
dog1.use_private()
8.8.4 多态
多态:多种形态,调用同一个函数,传入不同参数就会有不同表现
实现多态的步骤:
- 实现继承关系
- 子类重写父类方法
- 通过对象调用该方法
实例化子类:
dog=Dog()
cat = Cat()
方法 make_noise()定义时形参animal的类型是父类类型Animal
并在方法内调用父类子类都有的方法
但在真正调用方法时传入的实参是子类的实例对象
make_noise(dog)
make_noise(cat)
"""
1. 多态:多种形态,调用同一个函数,不同表现
2. 实现多态的步骤:
1. 实现继承关系
2. 子类重写父类方法
3. 通过对象调用该方法
"""
# 定义一个父类, Animal
class Animal(object):
def eat(self):
print('吃东西')
# 定义一个子类Dog,继承于Animal
class Dog(Animal):
def eat(self):
"""重写父类方法"""
print('啃骨头')
# 定义一个子类Cat,继承于Animal
class Cat(Animal):
def eat(self):
"""重写父类方法"""
print('吃小鱼')
# 定义一个函数,用于测试多态
def func(temp: Animal):
temp.eat()
# 创建子类对象
d = Dog()
c = Cat()
# 调用同一个函数,不同表现
# 传递d参数,调用Dog的eat()
# 传递c参数,调用Cat的eat()
func(d) # 啃骨头
func(c) # 吃小鱼
8.8.5 抽象基类
如果上面多态例子中父类不需要实例化,就可以直接把父类定义为抽象基类,把子类重写的方法定义成抽象实例方法(abstractmethod),不同子类根据自己的需求去实现这个方法即可。
抽象基类有两个特点:
1.规定继承类必须实现抽象基类指定的方法
2.抽象基类无法实例化
在Python的abc
模块中,ABC
和ABCMeta
是两个关键类,用于创建抽象基类(Abstract Base Class)。
ABC
(Abstract Base Class):
ABC
是一个可继承的基类,用于定义抽象基类。- 当一个类继承自
ABC
时,可以通过使用@abstractmethod
装饰器来定义抽象方法。- 抽象方法是一种声明,用于指示子类必须实现这些方法。
- 子类必须实现抽象基类中定义的所有抽象方法,否则在实例化时会引发
TypeError
异常。ABC
类本身并不强制要求实现任何方法或属性,它主要用于定义抽象方法和作为抽象基类的标识。
ABCMeta
(Abstract Base Class MetaClass):
ABCMeta
是一个元类(metaclass),用于定义抽象基类的元信息。- 通过将
ABCMeta
作为元类,可以在类定义阶段对类进行检查和修饰。ABCMeta
通过在类定义中使用metaclass
参数或在类的基类列表中包含ABCMeta
来指定。ABCMeta
元类提供了一些功能,例如检查子类是否实现了抽象方法、注册具体实现类等。
总结:
-
ABC
是一个可继承的基类,用于定义抽象基类,并通过装饰器@abstractmethod
定义抽象方法。-
ABCMeta
是一个元类,用于定义抽象基类的元信息,并提供了一些功能来检查和修饰类定义。
在实际使用中,通常通过继承ABC
类来创建抽象基类,并在类定义中指定ABCMeta
作为元类来实现抽象基类的功能。
from abc import ABC, abstractmethod, abstractproperty, abstractclassmethod, abstractstaticmethod
# 定义抽象基类需要导入abc包
class Human(ABC):
@abstractmethod # 规定子类必须有名为introduce的实例方法
def introduce(self):
pass
@abstractproperty # 规定子类必须有名为country的装饰器方法
def country(self):
pass
@abstractclassmethod # 规定子类必须有名为gender的类方法
def gender(cls):
pass
@abstractstaticmethod # 规定子类必须有名为hello的静态方法
def hello():
pass
class Person(Human):
__country = "China"
def __init__(self, name, age):
self.name = name
self.age = age
# 定义名为为introduce的实例方法
def introduce(self):
return "I'm {}, {}.".format(self.name, self.age)
# 定义名为country的装饰器方法
@property
def country(self):
return Person.__country
# 定义名为gender的类方法
@classmethod
def gender(cls):
return "female"
# 定义名为hello的静态方法
@staticmethod
def hello():
print("What the hell?")
person = Person("John", 22)
print(person.introduce())
print(person.country)
print(Person.gender())
person.hello()
# 输出内容如下:
# I'm John, 22.
# China
# female
# What the hell?
8.8.6 类型注解
1、变量的类型注解
可以在变量定义语句中进行类型注解,也可以把类型注解放在注释中
开发工具只会提示可能有错误
2、函数和方法的类型注解
3、Union联合类型 注解
8.8.7 属性类
指的是这个类中只有属性定义,没有方法,如下:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
对于这种类型的类,可以使用namedtuple()定义
namedtuple("类名", ["属性名1", "属性名2", ...])
Point = namedtuple("Test", ["x", "y","z"])
# 定义一个名称为Test的类。类只有属性:x y z
# 实例化 对应属性名代码会比较清晰
p1 = Point(x=1, y=2, z=3)
p2 = Point(x=1, y=2, z=4)
from collections import namedtuple
Point = namedtuple("Test", ["x", "y","z"])
# 定义一个名称为Test的类。类只有属性:x y z
# 实例化 对应属性名代码会比较清晰
p1 = Point(x=1, y=2, z=3)
p2 = Point(x=1, y=2, z=4)
# 实例化后实例对象的属性值就不能修改了,不然会报错
p1.x = 10 # AttributeError: can't set attribute
print(p1 == p2) # False
print(p1 < p2) # True
# 比较的是值不是地址
print(p1) # test(x=1, y=2, z=3)
print(type(p1)) # <class '__main__.Test'>
print(p1.x) # 1
# 使用id()获取对象的内存地址
print(id(p1)) # 31257648
print(id(p2)) # 35713976
补充:
1、python内置数据类型也可以使用继承
# python内置数据类型也可以使用继承
# 类Text继承了str
class Text(str):
def duplicate(self):
# 字符串拼接的方法可以继承
return self + self
str1 = Text()
print(str1) # 空字符串
str2 = Text("hello")
print(str2) # 传参后就是hello
print(str2.duplicate()) # hellohello
# 类TrackableList继承了list
class TrackableList(list):
def append(self, item):
print("在列表最后追加元素item")
super().append(item)
list1 = TrackableList()
print(list1) # 空列表 []
list2 = TrackableList([1, 2])
list2.append("hello")
print(list2) # [1, 2, 'hello']
2、对象的比较 判断的是对象的内存地址是否一致
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2) # False
# 使用id()获取对象的内存地址
print(id(p1)) # 31257648
print(id(p2)) # 35713976
如果想改变对象比较的默认逻辑,可以自行实现对应的magic method
A Guide to Python's Magic Methods « rafekettler.com
九、模块和包
9.1 模块
模块:modules
一个文件就是一个模块
9.1.1 模块的导入和使用
9.1.2 自定义模块
9.2 包
包:package
包就是文件夹,一个文件夹内可以有多个文件,一个包中可以有多个模块
9.2.1 自定义包
9.2.2 第三方包
9.3 练习
9.3.1 疫情确诊人数走势折线图
需要用到的第三方包 pyecharts
1、json数据格式
import json
data = [{"name": "小明", "age": 11}, {"name": "小红", "age": 13}, {"name": "小亮", "age": 15}]
json_str = json.dumps(data, ensure_ascii=False)
# 加上ensure_ascii=False 可以让给中文正常展示,不被转换
print(type(json_str)) # <class 'str'>
print(json_str)
# [{"name": "小明", "age": 11}, {"name": "小红", "age": 13}, {"name": "小亮", "age": 15}]
newdata = json.loads(json_str)
print(type(newdata)) # <class 'list'>
print(newdata)
# [{'name': '小明', 'age': 11}, {'name': '小红', 'age': 13}, {'name': '小亮', 'age': 15}]
2、pyecharts模块介绍
pyecharts 官网:
画廊:
3、pyecharts快速入门
# 基础折线图
# 导包 导入Line功能 构建折线图对象
from pyecharts.charts import Line
# 得到折线图对象
line = Line()
# 添加x轴数据
line.add_xaxis(["中国", "美国", "英国"])
# 添加y轴数据
line.add_yaxis("GDP", [30, 20, 10])
# 生成图表
line.render()
运行代码在同层目录会得到一个render.html,使用浏览器 打开就会得到如下折线图
全局配置选项:
set_global_opts方法:标题配置项TitleOpts、 图例配置项LegendOpts、工具箱配置项ToolboxOpts、视觉映射配置项VisualMapOpts、提示框配置项ToltipOpts、区域缩放配置项DatazoomOpts
# 基础折线图
# 导包 导入Line功能 构建折线图对象
from pyecharts.charts import Line
# 得到折线图对象
from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts, TooltipOpts
line = Line()
# 设置全局配置项
# 使用set_global_opts方法:
# 标题配置项TitleOpts、
# 图例配置项LegendOpts、
# 工具箱配置项ToolboxOpts、
# 视觉映射配置项VisualMapOpts、
# 提示框配置项TooltipOpts、
# 区域缩放配置项DatazoomOpts
line.set_global_opts(
title_opts=TitleOpts(title="GDP展示", pos_left="center", pos_bottom="1%"),
legend_opts=LegendOpts(is_show=True),
toolbox_opts=ToolboxOpts(is_show=True),
visualmap_opts=VisualMapOpts(is_show=True),
tooltip_opts=TooltipOpts(is_show=True),
)
# 添加x轴数据
line.add_xaxis(["中国", "美国", "英国"])
# 添加y轴数据
line.add_yaxis("GDP", [30, 20, 10])
# 生成图表
line.render()
4、数据处理
JSON在线 | JSON解析格式化—SO JSON在线工具
美国.txt
jsonp_1629344292311_69436({"status":0,"msg":"success","data":[{"name":"美国","trend":{"updateDate":["2.22","2.23","2.24","2.25","2.26","2.27","2.28","2.29","3.1","3.2","3.3","3.4","3.5","3.6","3.7","3.8","3.9","3.10","3.11","3.12","3.13","3.14","3.15","3.16","3.17","3.18","3.19","3.20","3.21","3.22","3.23","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","4.1","4.2","4.3","4.4","4.5","4.6","4.7","4.8","4.9","4.10","4.11","4.12","4.13","4.14","4.15","4.16","4.17","4.18","4.19","4.20","4.21","4.22","4.23","4.24","4.25","4.26","4.27","4.28","4.29","4.30","5.1","5.2","5.3","5.4","5.5","5.6","5.7","5.8","5.9","5.10","5.11","5.12","5.13","5.14","5.15","5.16","5.17","5.18","5.19","5.20","5.21","5.22","5.23","5.24","5.25","5.26","5.27","5.28","5.29","5.30","5.31","6.1","6.2","6.3","6.4","6.5","6.6","6.7","6.8","6.9","6.10","6.11","6.12","6.13","6.14","6.15","6.16","6.17","6.18","6.19","6.20","6.21","6.22","6.23","6.24","6.25","6.26","6.27","6.28","6.29","6.30","7.1","7.2","7.3","7.4","7.5","7.6","7.7","7.8","7.9","7.10","7.11","7.12","7.13","7.14","7.15","7.16","7.17","7.18","7.19","7.20","7.21","7.22","7.23","7.24","7.25","7.26","7.27","7.28","7.29","7.30","7.31","8.1","8.2","8.3","8.4","8.5","8.6","8.7","8.8","8.9","8.10","8.11","8.12","8.13","8.14","8.15","8.16","8.17","8.18","8.19","8.20","8.21","8.22","8.23","8.24","8.25","8.26","8.27","8.28","8.29","8.30","8.31","9.1","9.2","9.3","9.4","9.5","9.6","9.7","9.8","9.9","9.10","9.11","9.12","9.13","9.14","9.15","9.16","9.17","9.18","9.19","9.20","9.21","9.22","9.23","9.24","9.25","9.26","9.27","9.28","9.29","9.30","10.1","10.2","10.3","10.4","10.5","10.6","10.7","10.8","10.9","10.10","10.11","10.12","10.13","10.14","10.15","10.16","10.17","10.18","10.19","10.20","10.21","10.22","10.23","10.24","10.25","10.26","10.27","10.28","10.29","10.30","10.31","11.1","11.2","11.3","11.4","11.5","11.6","11.7","11.8","11.9","11.10","11.11","11.12","11.13","11.14","11.15","11.16","11.17","11.18","11.19","11.20","11.21","11.22","11.23","11.24","11.25","11.26","11.27","11.28","11.29","11.30","12.1","12.2","12.3","12.4","12.5","12.6","12.7","12.8","12.9","12.10","12.11","12.12","12.13","12.14","12.15","12.16","12.17","12.18","12.19","12.20","12.21","12.22","12.23","12.24","12.25","12.26","12.27","12.28","12.29","12.30","12.31","1.1","1.2","1.3","1.4","1.5","1.6","1.7","1.8","1.9","1.10","1.11","1.12","1.13","1.14","1.15","1.16","1.17","1.18","1.19","1.20","1.21","1.22","1.23","1.24","1.25","1.26","1.27","1.28","1.29","1.30","1.31","2.1","2.2","2.3","2.4","2.5","2.6","2.7","2.8","2.9","2.10","2.11","2.12","2.13","2.14","2.15","2.16","2.17","2.18","2.19","2.20","2.21","2.22","2.23","2.24","2.25","2.26","2.27","2.28","3.1","3.2","3.3","3.4","3.5","3.6","3.7","3.8","3.9","3.10","3.11","3.12","3.13","3.14","3.15","3.16","3.17","3.18","3.19","3.20","3.21","3.22","3.23","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","4.1","4.2","4.3","4.4","4.5","4.6","4.7","4.8","4.9","4.10","4.11","4.12","4.13","4.14","4.15","4.16","4.17","4.18","4.19","4.20","4.21","4.22","4.23","4.24","4.25","4.26","4.27","4.28","4.29","4.30","5.1","5.2","5.3","5.4","5.5","5.6","5.7","5.8","5.9","5.10","5.11","5.12","5.13","5.14","5.15","5.16","5.17","5.18","5.19","5.20","5.21","5.22","5.23","5.24","5.25","5.26","5.27","5.28","5.29","5.30","5.31","6.1","6.2","6.3","6.4","6.5","6.6","6.7","6.8","6.9","6.10","6.11","6.12","6.13","6.14","6.15","6.16","6.17","6.18","6.19","6.20","6.21","6.22","6.23","6.24","6.25","6.26","6.27","6.28","6.29","6.30","7.1","7.2","7.3","7.4","7.5","7.6","7.7","7.8","7.9","7.10","7.11","7.12","7.13","7.14","7.15","7.16","7.17","7.18","7.19","7.20","7.21","7.22","7.23","7.24","7.25","7.26","7.27","7.28","7.29","7.30","7.31","8.1","8.2","8.3","8.4","8.5","8.6","8.7","8.8","8.9","8.10","8.11","8.12","8.13","8.14","8.15","8.16","8.17","8.18"],"list":[{"name":"确诊","data":[34,34,34,53,57,60,60,64,69,89,106,125,161,233,345,445,572,717,1010,1322,1264,1678,3499,4629,5894,9345,14250,19624,22043,32717,46332,53268,65285,83507,101657,121117,139675,161367,184183,206207,236339,270473,312076,334125,363349,394182,425828,463433,498674,530384,559245,586941,610632,641397,674829,710021,738697,762496,789383,825306,844992,877497,916348,955488,985060,1004942,1029878,1056646,1092656,1125305,1156744,1185167,1209702,1234592,1256639,1289028,1318686,1342723,1365308,1381665,1406519,1427587,1453381,1480975,1503684,1526134,1532861,1555133,1573778,1597130,1627409,1650677,1672527,1689727,1711569,1730595,1750377,1772643,1797949,1822117,1842243,1862879,1887708,1907840,1928026,1973883,1995854,2012001,2030323,2052816,2072274,2094368,2123102,2150245,2166685,2188198,2215580,2242914,2275218,2303692,2342597,2363825,2396101,2426500,2474962,2511784,2571448,2615417,2649774,2695685,2744570,2797737,2855961,2909123,2948587,2996027,3055548,3116430,3174924,3242086,3311844,3381274,3436152,3490706,3565476,3642907,3719446,3790373,3854368,3901026,3979579,4046552,4118684,4197515,4273303,4333464,4384069,4451396,4515787,4570103,4655611,4729242,4778177,4821556,4873925,4925454,4988431,5041384,5108144,5164221,5212499,5263777,5321984,5365527,5427637,5478009,5539841,5573475,5614889,5663371,5710773,5757944,5809339,5848860,5886045,5923582,5967010,6013451,6059951,6103820,6141778,6177207,6214690,6260881,6302203,6341126,6400670,6434850,6466100,6490632,6521356,6559509,6594419,6645500,6684292,6718969,6753195,6797153,6838556,6880182,6932328,6972440,7011038,7053783,7106699,7148986,7196972,7251328,7294643,7325115,7365427,7413600,7457857,7507524,7564910,7607545,7644713,7687269,7730931,7787879,7842831,7909037,7957615,8000852,8049854,8106263,8165007,8230184,8306024,8351444,8393773,8468223,8528732,8595023,8675199,8769097,8839609,8898410,8976435,9053778,9136784,9226558,9336073,9414641,9487088,9574004,9702484,9806960,9937271,10071095,10191335,10297867,10433356,10579938,10725002,10888324,11078662,11235666,11381956,11545530,11699233,11896039,12094052,12293770,12463498,12598889,12786174,12978833,13150740,13466984,13612512,13750608,13920038,13933653,14131866,14333241,14568192,14784825,14995863,15169648,15383380,15609610,15845642,16073829,16308192,16563650,16752408,16958845,17159794,17414880,17654984,17899267,18086215,18285335,18494265,18691742,18937716,19117212,19217816,19573847,19781624,19803605,19990823,20237964,20462501,20619032,20918061,21118056,21365185,21610422,21869885,22166149,22492589,22714728,22935771,23155164,23386010,23632112,23870669,24110448,24315314,24488739,24632518,24818518,25023343,25211649,25397214,25579523,25713893,25870814,26030906,26192314,26359244,26518148,26663198,26771042,26916617,27036145,27162000,27278671,27412193,27527512,27616951,27704111,27806679,27906565,28010156,28111899,28203185,28262656,28320708,28386112,28455519,28529053,28606256,28708395,28769345,28833194,28903679,28981169,29059531,29139466,29203913,29259111,29317873,29375702,29458725,29529369,29599380,29656182,29698316,29746358,29802437,29864187,29929048,29994880,30046127,30084925,30141986,30235739,30301478,30365645,30430839,30485146,30525546,30584133,30642156,30712693,30780446,30858924,30924489,30971471,31038713,31105552,31171824,31254320,31319713,31385250,31425966,31505372,31564041,31648458,31729532,31805293,31872934,31924090,32004871,32081119,32159704,32229561,32311824,32367532,32410664,32482069,32545506,32608235,32674864,32738575,32791704,32826166,32877124,32929328,32989068,33045026,33111880,33147944,33182584,33235845,33279375,33326362,33372079,33423238,33456075,33479348,33519192,33552055,33589578,33628266,33669344,33697379,33718260,33747850,33776970,33804454,33835634,33862888,33882787,33898195,33924707,33949445,33974288,33999993,34022949,34036447,34043227,34114420,34137548,34154767,34176367,34192759,34204478,34211228,34228382,34243135,34266374,34276819,34306726,34316178,34321723,34335515,34353097,34366709,34378217,34393372,34402047,34406337,34420165,34435231,34449692,34465568,34482925,34490231,34495082,34512206,34527963,34541123,34561470,34580470,34588360,34592415,34600300,34622850,34647863,34677466,34711770,34726259,34733644,34766952,34808130,34849074,34888864,34930095,34953937,34964151,35019526,35082335,35147918,35149096,35212393,35251453,35287269,35288544,35355430,35491609,35588314,35689184,35745024,35771553,35900045,36056093,36189636,36305074,36449535,36519801,36543924,36780842,36896358,37067806,37210382,37365716,37435835,37468530,37739987,37909829]},{"name":"治愈","data":[0,0,3,0,0,0,0,0,0,0,3,3,8,8,10,10,10,10,10,15,41,56,56,56,56,106,121,147,147,178,178,178,378,680,869,961,2661,5595,6043,8434,8861,9445,14997,16848,19313,21571,23292,25139,27744,29444,32091,36948,38562,48105,57256,60510,68269,69956,72015,82973,83910,85021,93275,116167,118735,137591,140138,145320,151774,160173,161782,178219,184354,199151,205268,215580,222008,232869,240853,260188,280509,307755,316244,321348,337563,344805,347225,359137,361419,371077,383099,403315,447211,451749,467962,480321,490262,499768,519736,536234,600150,615719,646614,689282,712437,738998,752848,761736,773696,788969,808556,817337,842329,854659,870080,891068,903176,919108,931355,956316,974746,980836,1003322,1020499,1040711,1052529,1069342,1081793,1093951,1122678,1143923,1168436,1191892,1237767,1260695,1291315,1326669,1355898,1393363,1426645,1461374,1501866,1518254,1551021,1601508,1646933,1681060,1751902,1775491,1802550,1851157,1889285,1943698,1982124,2035976,2061879,2090298,2139817,2190356,2246212,2286492,2331327,2363229,2381407,2449120,2483903,2541859,2579191,2618203,2639927,2667649,2717642,2758382,2813845,2844525,2876080,2904440,2924268,2974788,3012244,3063412,3097040,3127665,3148165,3168960,3219333,3257748,3315120,3350304,3376815,3409063,3425925,3458244,3498209,3548122,3575866,3637002,3707191,3726119,3759134,3797941,3856749,3882295,3919169,3950648,3981346,4029477,4069609,4120577,4156472,4192963,4223996,4251943,4301523,4360093,4400872,4440485,4483950,4524760,4571265,4611282,4651017,4711997,4750176,4779402,4828654,4862023,4906808,4950141,4997380,5026952,5066257,5092941,5138374,5197125,5238565,5290510,5329151,5402456,5438389,5463410,5513584,5549360,5612505,5662998,5704352,5742963,5781451,5842665,5885393,5940558,5986309,6030186,6066893,6109683,6173165,6237659,6294444,6342279,6392425,6442590,6484054,6554526,6603478,6651545,6729527,6790898,6891461,6939835,7023230,7090336,7171883,7248771,7320373,7405265,7453661,7553556,7641913,7809461,7945585,8041239,8107270,8223391,8230001,8345995,8468702,8570636,8663942,8790495,8859465,8994191,9095080,9235316,9340223,9511911,9645924,9727555,9879331,10015012,10176485,10296261,10399339,10546751,10623101,10807172,10949574,11104857,11219489,11260932,11495875,11696727,11701029,11848630,12004898,12129680,12179238,12364189,12438638,12740254,12867806,13027453,13149021,13262863,13395752,13485260,13686114,13822268,13989184,14116779,14232377,14345507,14429670,14554257,14789811,14971903,15102060,15222909,15332896,15410579,15621586,15769146,15946080,16073346,16205134,16331248,16404678,16632859,16754190,16910071,17034751,17155139,17270463,17355083,17531152,17643640,17829681,17932117,18042270,18153841,18225135,18360050,18482067,18598301,18705426,18803870,18899383,18973605,19123743,19213237,19351989,19437119,19534420,19632572,19694344,19817630,19906113,20003419,20094343,20183964,20273917,20337124,20449894,20549683,20640748,20791322,22031315,22108944,22169286,22286801,22359523,22448224,22524157,22610516,22683821,22754337,22849905,23040302,23133605,23196688,23275549,23348808,23412337,23512386,23587883,23674274,23755003,23826158,23894933,23946970,24061534,24122758,24207348,24273615,24352334,24423693,24483025,24564313,24627180,24697102,24771510,24836442,24912339,24963753,25043528,25106084,25177498,25237089,25296330,25339994,25379860,25477692,25522166,25585578,25642151,25713185,25777927,25823932,25912151,25967231,26035399,26105941,26325307,26405895,26440056,26508144,26558229,26620848,26667224,26713260,27098665,27137693,27202318,27253889,27299310,27358685,27399429,27471314,27502275,27564594,27606705,27662791,27701879,27767062,27819783,27840884,27864919,27942476,27986542,28026136,28055012,28103496,28122741,28179158,28221041,28254425,28278647,28346340,28381635,28400648,28438183,28579129,28616860,28641443,28675967,28695025,28711321,28768408,28817445,28846409,28871917,28897490,28913044,28927336,28963939,29007495,29026760,29052212,29072893,29087424,29096816,29111901,29145393,29168406,29203311,29222972,29234930,29244103,29274450,29304606,29324310,29342095,29358531,29369181,29376745,29407667,29435550,29458707,29478193,29497875,29507123,29511917,29548607,29571650,29604525,29626891,29652042,29666117,29673543,29720758,29756608,29787468,29805593,29834481,29851804,29859073,29923320,29966351,30050065,30097898,30130093,30144609,30153948,30227303,30290005]},{"name":"死亡","data":[0,0,0,0,0,0,0,0,1,2,6,9,11,14,17,19,22,26,31,38,36,41,62,90,97,150,205,260,278,409,552,696,926,1201,1581,2010,2436,2956,3606,4542,5648,6889,8496,9458,10755,12716,14604,16504,18509,20513,22036,23640,25856,28394,34475,37158,39011,40478,42303,45343,47430,49729,51742,54120,55357,56527,58640,61180,63765,65540,67228,68495,69476,72054,74121,76791,78498,79926,80717,81552,83262,85029,86770,88309,89454,90931,91092,92198,93707,95118,96683,97800,98792,99381,99987,100825,102293,103452,104634,105680,106302,107135,108291,109271,110331,111599,112187,112596,113267,114379,115291,116138,116952,117587,117902,118487,119269,120079,120844,121520,122067,122292,122764,123521,124422,126911,127803,128233,128503,129031,130345,130984,131666,132174,132374,132664,133268,134163,135189,136024,136949,137577,137863,138459,139447,140460,141432,142400,143012,143321,144220,145271,146500,147676,148848,149541,149945,151478,152729,153887,155746,157184,158039,158457,159386,160502,161895,162975,164377,165235,165766,166707,168253,169225,170734,171568,172762,173187,173804,175429,176628,177652,179489,180295,180720,181479,182817,183931,185160,186179,186883,187248,187839,188975,190300,191221,192308,192887,193283,193648,194381,195590,196412,197629,198189,198643,199216,200667,201631,202306,203274,203881,204165,204801,205864,206895,207794,208625,209238,209502,209922,211098,211988,212912,213684,214341,214697,215221,216064,217081,217857,218855,219341,219797,220281,221147,222092,222973,223885,224389,224824,225451,226360,227516,228577,229551,230126,230556,231308,232305,233340,234405,235453,236154,236564,237068,238746,239894,241126,242339,243316,243807,244589,246034,247537,248686,250105,251285,251965,252792,254329,256609,258655,260479,261885,262757,263899,266285,268439,271038,272253,273077,274332,274743,277396,280210,283300,285786,287894,288984,291016,293739,297173,300272,302904,305144,306529,308335,311316,314991,318413,321025,323466,324915,327171,330921,334415,337081,338324,341138,343182,343593,346955,351127,354381,356450,358745,360151,362538,366252,370151,374624,378559,381557,383461,385534,390126,394308,398370,401980,405351,407256,408687,411657,416435,420719,424275,427713,429560,431818,436130,440257,444127,447558,450478,452332,454323,458341,462236,467109,470824,473586,475017,476553,479897,483487,487171,492663,496099,497177,498258,500159,502586,505474,507795,509916,511320,513051,515333,518803,520980,523142,524690,525795,527553,529307,531682,533680,535765,537214,537854,538711,540574,542230,543756,545555,546661,547300,548091,549484,550761,552564,554158,554899,555339,556070,556969,558497,559897,561199,562083,562582,563271,564336,565308,566733,567697,568524,568834,569425,570306,573016,573988,574893,575610,575853,576489,577273,578223,579053,580041,580823,581086,581665,582599,583427,584310,585115,585909,586177,586650,587441,588412,589222,590153,590733,591088,591610,592511,593244,594059,594981,595612,595845,596265,596989,597845,598574,599317,599937,600174,600548,601398,602009,602656,603446,603896,604113,604478,605278,606257,607732,608968,609442,609551,609777,610489,611037,611667,612265,612209,612378,612759,613084,613542,614054,614755,614972,615061,615247,615770,616174,616461,616924,617109,617174,617514,617893,618321,618694,619162,619347,619433,619619,619992,620267,620648,621172,621257,621295,621371,621563,621926,622219,622715,622825,622848,623044,623450,623867,624240,624612,624715,624746,624998,625403,625852,626187,626664,626713,626769,627048,627370,628131,628513,629072,629315,629387,629913,630532,631355,631899,632647,632995,633120,633799,634688,635257,636345,637170,637439,637567,638830,640181]},{"name":"新增确诊","data":[23,0,0,19,4,3,0,4,5,12,17,19,36,72,112,100,127,145,293,312,277,414,255,860,826,2769,5892,5374,5374,6670,10497,10054,12017,14886,19253,20400,18500,21692,21371,22741,25508,28048,32467,22768,26676,27178,25493,28506,30108,26272,24751,23570,23691,27511,26826,22566,28962,23704,24747,23577,26248,27457,38958,30256,24409,19882,24936,26768,36010,30282,25714,19299,21580,21757,19006,25936,26063,20938,17999,14027,20685,18951,23033,23382,19399,18361,6727,22272,18645,23352,30279,23268,21850,17200,21842,19026,19782,22266,25306,24168,20126,20636,24829,20132,20186,45857,21971,16147,18322,22493,19458,22094,28734,27143,16440,21513,27382,27334,32304,28474,38905,21228,32276,30399,48462,36822,59664,43969,34357,45911,48885,53167,58224,53162,39464,47440,59521,60882,58494,67162,69758,69430,54878,54554,74770,77431,76539,70927,63995,46658,78553,66973,72132,78831,75788,60161,50605,67327,64391,54316,85508,73631,48935,43379,52369,51529,62977,52953,66760,56077,48278,51278,58207,43543,62110,50372,61832,33634,41414,48482,47402,47171,51395,39521,37185,37537,43428,46441,46500,43869,37958,35429,37483,46191,41322,38923,59544,34180,31250,24532,30724,38153,34910,51081,38792,34677,34226,43958,41403,41626,52146,40112,38598,42745,52916,42287,47986,54356,43315,30472,40312,48173,44257,49667,57386,42635,37168,42556,43662,56948,54952,66206,48578,43237,49002,56409,58744,65177,75840,45420,42329,74450,60509,66291,80176,93898,70512,58801,78025,77343,83006,89774,109515,78568,72447,86916,128480,104476,130311,133824,120240,106532,135489,146582,145064,163322,190338,157004,146290,163574,153703,196806,198013,199718,169728,135391,187285,192659,171907,46567,145528,138096,138370,13615,198213,201375,234951,216633,211038,173785,213732,226230,236032,228187,234363,255458,188758,206437,200949,255086,240104,244283,186948,199120,208930,197477,245974,179496,100604,356031,207777,21981,187218,247141,224537,156531,299029,199995,247129,245237,259463,296264,326440,222139,221043,219393,230846,246102,238557,239779,204866,173425,143779,186000,204825,188306,185565,182309,134370,156921,160092,161408,166930,158904,145050,107844,145575,119528,125855,116671,133522,115319,89439,87160,102568,99886,103591,101743,91286,59471,58052,65404,69407,73534,77203,102139,60950,63849,70485,77490,78362,79935,64447,55198,58762,57829,83023,70644,70011,56802,42134,48042,56079,61750,64861,65832,51247,38798,57061,93753,65739,64167,65194,54307,40400,58587,58023,70537,67753,78478,65565,46982,67242,66839,66272,82496,65393,65537,40716,79406,58669,84417,81074,75761,67641,51156,80781,76248,78585,69857,82263,55708,43132,71405,63437,62729,66629,63711,53129,34462,50958,52204,59740,55958,66854,36064,34640,53261,43530,46987,45717,51159,32837,23273,39844,32863,37523,38688,41078,28035,20881,29590,29120,27484,31180,27254,19899,15408,26512,24738,24843,25705,22956,13498,6780,71193,23128,17219,21600,16392,11719,6750,17154,14753,23239,10445,29907,9452,5545,13792,17582,13612,11508,15155,8675,4290,13828,15066,14461,15876,17357,7306,4851,17124,15757,13160,20347,19000,7890,4055,7885,22550,25013,29603,34304,14489,7385,33308,41178,40944,39790,41231,23842,10214,55375,62809,65583,69382,63297,39060,35816,1275,66886,136179,96705,100870,55840,26529,128492,156048,133543,115438,144461,70266,24123,236918,115516,171448,142576,155334,70119,32695,271457,169842]}]}}]});
日本.txt
jsonp_1629350871167_29498({"status":0,"msg":"success","data":[{"name":"日本","trend":{"updateDate":["2.21","2.22","2.23","2.24","2.25","2.26","2.27","2.28","2.29","3.1","3.2","3.3","3.4","3.5","3.6","3.7","3.8","3.9","3.10","3.11","3.12","3.13","3.14","3.15","3.16","3.17","3.18","3.19","3.20","3.21","3.22","3.23","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","4.1","4.2","4.3","4.4","4.5","4.6","4.7","4.8","4.9","4.10","4.11","4.12","4.13","4.14","4.15","4.16","4.17","4.18","4.19","4.20","4.21","4.22","4.23","4.24","4.25","4.26","4.27","4.28","4.29","4.30","5.1","5.2","5.3","5.4","5.5","5.6","5.7","5.8","5.9","5.10","5.11","5.12","5.13","5.14","5.15","5.16","5.17","5.18","5.19","5.20","5.21","5.22","5.23","5.24","5.25","5.26","5.27","5.28","5.29","5.30","5.31","6.1","6.2","6.3","6.4","6.5","6.6","6.7","6.8","6.9","6.10","6.11","6.12","6.13","6.14","6.15","6.16","6.17","6.18","6.19","6.20","6.21","6.22","6.23","6.24","6.25","6.26","6.27","6.28","6.29","6.30","7.1","7.2","7.3","7.4","7.5","7.6","7.7","7.8","7.9","7.10","7.11","7.12","7.13","7.14","7.15","7.16","7.17","7.18","7.19","7.20","7.21","7.22","7.23","7.24","7.25","7.26","7.27","7.28","7.29","7.30","7.31","8.1","8.2","8.3","8.4","8.5","8.6","8.7","8.8","8.9","8.10","8.11","8.12","8.13","8.14","8.15","8.16","8.17","8.18","8.19","8.20","8.21","8.22","8.23","8.24","8.25","8.26","8.27","8.28","8.29","8.30","8.31","9.1","9.2","9.3","9.4","9.5","9.6","9.7","9.8","9.9","9.10","9.11","9.12","9.13","9.14","9.15","9.16","9.17","9.18","9.19","9.20","9.21","9.22","9.23","9.24","9.25","9.26","9.27","9.28","9.29","9.30","10.1","10.2","10.3","10.4","10.5","10.6","10.7","10.8","10.9","10.10","10.11","10.12","10.13","10.14","10.15","10.16","10.17","10.18","10.19","10.20","10.21","10.22","10.23","10.24","10.25","10.26","10.27","10.28","10.29","10.30","10.31","11.1","11.2","11.3","11.4","11.5","11.6","11.7","11.8","11.9","11.10","11.11","11.12","11.13","11.14","11.15","11.16","11.17","11.18","11.19","11.20","11.21","11.22","11.23","11.24","11.25","11.26","11.27","11.28","11.29","11.30","12.1","12.2","12.3","12.4","12.5","12.6","12.7","12.8","12.9","12.10","12.11","12.12","12.13","12.14","12.15","12.16","12.17","12.18","12.19","12.20","12.21","12.22","12.23","12.24","12.25","12.26","12.27","12.28","12.29","12.30","12.31","1.1","1.2","1.3","1.4","1.5","1.6","1.7","1.8","1.9","1.10","1.11","1.12","1.13","1.14","1.15","1.16","1.17","1.18","1.19","1.20","1.21","1.22","1.23","1.24","1.25","1.26","1.27","1.28","1.29","1.30","1.31","2.1","2.2","2.3","2.4","2.5","2.6","2.7","2.8","2.9","2.10","2.11","2.12","2.13","2.14","2.15","2.16","2.17","2.18","2.19","2.20","2.21","2.22","2.23","2.24","2.25","2.26","2.27","2.28","3.1","3.2","3.3","3.4","3.5","3.6","3.7","3.8","3.9","3.10","3.11","3.12","3.13","3.14","3.15","3.16","3.17","3.18","3.19","3.20","3.21","3.22","3.23","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","4.1","4.2","4.3","4.4","4.5","4.6","4.7","4.8","4.9","4.10","4.11","4.12","4.13","4.14","4.15","4.16","4.17","4.18","4.19","4.20","4.21","4.22","4.23","4.24","4.25","4.26","4.27","4.28","4.29","4.30","5.1","5.2","5.3","5.4","5.5","5.6","5.7","5.8","5.9","5.10","5.11","5.12","5.13","5.14","5.15","5.16","5.17","5.18","5.19","5.20","5.21","5.22","5.23","5.24","5.25","5.26","5.27","5.28","5.29","5.30","5.31","6.1","6.2","6.3","6.4","6.5","6.6","6.7","6.8","6.9","6.10","6.11","6.12","6.13","6.14","6.15","6.16","6.17","6.18","6.19","6.20","6.21","6.22","6.23","6.24","6.25","6.26","6.27","6.28","6.29","6.30","7.1","7.2","7.3","7.4","7.5","7.6","7.7","7.8","7.9","7.10","7.11","7.12","7.13","7.14","7.15","7.16","7.17","7.18","7.19","7.20","7.21","7.22","7.23","7.24","7.25","7.26","7.27","7.28","7.29","7.30","7.31","8.1","8.2","8.3","8.4","8.5","8.6","8.7","8.8","8.9","8.10","8.11","8.12","8.13","8.14","8.15","8.16","8.17","8.18"],"list":[{"name":"确诊","data":[93,105,132,144,156,164,186,210,230,239,254,268,284,317,348,407,454,522,582,640,690,726,787,818,835,880,923,962,1016,1054,1101,1140,1212,1313,1401,1525,1724,1894,1999,2233,2524,2793,3142,3506,3865,4092,4472,4979,5553,6188,6926,7423,7693,8191,8723,9297,9849,10434,10810,11157,11581,12023,12480,12868,13238,13441,13614,13895,14119,14305,14571,14877,15079,15253,15374,15477,15575,15663,15777,15847,15968,16049,16120,16203,16253,16310,16337,16367,16394,16433,16518,16543,16569,16611,16632,16662,16696,16759,16833,16877,16912,16949,17000,17031,17078,17118,17164,17202,17223,17268,17306,17347,17404,17454,17529,17601,17645,17689,17759,17816,17881,17937,17982,18034,18130,18212,18317,18409,18522,18631,18769,18895,19090,19329,19602,19822,19998,20209,20413,20767,21179,21581,21991,22252,22583,23008,23645,24235,24916,25425,25844,26476,27270,28200,28984,29782,30656,31249,32244,33474,34809,36366,37925,39255,40212,41455,42804,44286,45889,47464,48817,49746,50444,51425,52602,53961,55193,56214,56854,57761,58848,60033,61066,62046,62790,63283,64000,64897,65763,66638,67488,68088,68516,69151,69743,70405,70994,71585,72037,72321,72833,73337,74026,74688,75334,75774,76039,76571,77121,77650,78182,78782,79260,79571,79902,80116,80592,81169,81806,82285,82583,83115,83689,84335,84874,85451,85851,86135,86635,87145,87762,88374,89054,89491,89769,90269,90818,91526,92167,92787,93219,93533,94015,94634,95248,95995,96720,97218,97617,98262,98995,99804,100577,101453,102068,102548,103413,104036,105082,106221,107557,108503,109280,110616,112164,113808,115518,117261,118702,119652,121336,123544,125932,128348,130941,133117,134635,135846,137786,140288,142818,145502,147568,149002,151018,153456,155964,158411,160917,162942,164462,166618,169431,172416,175207,178242,180630,182305,184732,187718,190935,193757,196746,199248,201048,203717,206984,210723,214553,218430,223766,223771,227375,231223,235751,238999,242052,245212,248531,253432,259438,267004,274883,282662,288751,293637,298168,304040,310627,317772,324785,330544,335465,340780,346309,351976,357021,361733,365723,368485,372332,376300,380427,383958,387303,389975,391763,394087,396716,399289,401661,403938,405562,406775,408345,410231,411921,413219,414582,415945,417746,419050,420497,422035,423336,424568,425600,426375,427457,428376,429453,430509,431722,432720,433417,434304,435547,436717,437862,438916,439981,440580,441706,443018,444297,445606,446923,447912,448606,449739,451272,452771,454232,455747,456865,457686,459176,461101,463015,465040,467112,468896,470233,472325,475168,477774,480532,483305,485775,487346,489986,493448,496890,500422,504113,506895,508994,512703,517013,521586,526117,530903,534996,537898,542248,547544,553037,558145,563748,568353,571672,576626,582411,588308,593002,598988,604885,609353,613552,617622,621981,628034,635281,641761,646698,652935,659986,666851,673109,679530,684790,688464,693686,699504,705221,710471,715510,719556,722226,726117,730646,734784,738488,742080,744956,746745,749386,752419,755244,757839,760490,762511,763785,765668,767906,769949,771878,773821,773821,776139,777557,779262,780814,782432,783950,785257,786125,787536,789313,790983,792690,794321,795603,796603,797981,799801,801553,803324,805205,806690,807719,809385,811575,813821,816097,818553,820584,822088,824473,827667,831080,834511,838397,841499,843827,847585,852528,857921,862143,865717,870737,875427,883054,892628,903324,914065,926405,936581,944970,956986,971192,986451,1002093,1017842,1032249,1044320,1054890,1070698,1089548,1109912,1130059,1147889,1162736,1182686,1206597]},{"name":"治愈","data":[23,24,24,26,27,32,40,41,42,42,43,46,48,48,69,76,80,101,102,118,123,135,144,144,144,144,215,215,215,215,215,285,301,310,359,372,372,372,424,424,472,505,514,514,575,575,622,632,685,714,714,762,799,853,901,918,1012,1069,1069,1239,1356,1424,2408,2536,2536,2536,2905,3187,3187,3466,3981,3981,3981,4496,4587,4918,5146,5906,8127,8293,8531,8920,9868,10338,10809,11153,11415,11564,11884,12286,12672,13005,13244,13244,13612,13810,13973,14147,14254,14406,14459,14502,14650,14771,14869,14972,14972,14972,15148,15213,15298,15383,15493,15580,15643,15686,15701,15850,15930,16008,16077,16108,16133,16212,16263,16320,16392,16452,16506,16557,16631,16731,16772,16866,16959,17050,17124,17197,17331,17466,17652,17849,18003,18103,18282,18545,18814,19096,19366,19576,19757,20155,20651,21035,21328,21567,21762,22116,22811,23507,24179,24929,25506,25906,26487,27197,28028,28877,30153,31307,32312,33058,33975,34888,36134,37479,38945,40080,41196,42284,43835,45266,46467,47622,48550,49340,50431,51688,52823,53995,55341,56164,56802,57823,58428,59524,60417,61445,62076,62536,63282,64100,64835,65590,66280,66899,67242,67831,68532,69253,69899,70495,71030,71404,71648,71981,72538,73490,74151,74607,74990,75459,76025,76590,77219,77807,78315,78609,79071,79676,80227,80733,81356,81824,82113,82621,83158,83837,84451,85030,85485,85941,86513,87107,87666,88245,88787,89282,89709,90148,90807,91322,91890,92475,92960,93383,93855,94295,95113,95756,96461,97197,97654,98274,99108,100005,101018,101989,102837,103674,104637,105697,106954,108423,109892,111163,112269,113340,114725,116378,118135,120259,121891,123445,125470,127304,129241,131176,133443,135277,136903,138994,140622,143006,145014,147524,149286,150947,153519,155547,158287,160786,163308,165333,167513,169342,172115,174879,177793,180188,184662,184662,186946,189466,191451,193714,196420,198486,200676,203421,207039,210451,213737,217369,220536,222963,225396,229073,233665,238467,243973,248488,252787,257719,264987,273187,279214,285522,290542,295426,301540,308164,314434,320248,325592,330465,334125,339377,344137,349332,354473,358872,362231,365238,368813,372535,375454,378024,380569,382886,385097,387740,391208,393494,395492,397293,398921,400250,401809,403381,405257,406584,408020,409319,410604,412115,413334,414774,416024,417292,418261,419229,420260,421421,422542,423619,424685,425663,426686,427582,428783,429898,430927,432128,433149,434274,435361,436463,437702,438879,440200,441237,442369,443640,445024,446416,447715,449091,450624,452155,454055,455382,457050,458840,460993,463725,465916,468770,471007,473570,475574,478378,480793,483052,486076,488944,491661,494882,498242,501609,504738,508388,512069,515560,519047,523227,527233,531069,534836,538946,542569,546042,551293,555401,559553,564128,568558,573913,579446,584770,590044,595177,602356,609086,615324,621608,628522,634103,639887,645157,650111,655222,659732,666942,671772,675877,680621,685365,690623,695010,699741,703525,706644,710216,713807,717882,721260,724804,724804,730446,733316,736941,740213,742848,746431,748631,750430,752427,754334,756293,758173,760243,761912,763364,764913,766616,768328,770008,771784,773480,775042,776646,778492,780011,781613,783429,784992,786581,788131,789905,791751,793643,795388,797208,799062,801337,803681,806202,808413,810884,814024,816875,820138,823901,827372,831087,834967,839246,842780,847873,852607,858461,864775,873519,881608,889912,899124,909741,920862,930799,943260,955251,968380,982640,997295]},{"name":"死亡","data":[1,1,1,1,1,1,3,4,5,5,6,6,6,6,6,6,6,9,12,15,19,21,22,24,28,29,32,33,35,36,41,42,43,45,47,52,55,56,59,66,71,73,78,83,93,97,98,105,108,120,132,138,146,162,179,190,207,224,238,265,283,299,328,345,360,372,394,413,435,455,481,517,536,556,566,577,590,607,624,633,657,678,697,713,729,748,756,768,773,784,799,814,825,839,851,860,869,882,889,894,897,898,901,905,910,914,916,916,919,920,922,922,925,927,927,929,934,935,937,954,954,955,956,965,969,971,971,972,972,972,972,976,977,977,977,977,978,979,982,982,982,983,983,984,984,984,985,985,986,986,988,989,989,992,994,996,998,998,1002,1004,1007,1010,1013,1013,1017,1022,1028,1035,1040,1042,1047,1053,1058,1066,1073,1085,1093,1103,1119,1135,1149,1159,1175,1181,1190,1203,1217,1228,1241,1251,1285,1286,1298,1313,1327,1334,1352,1361,1366,1380,1397,1412,1416,1428,1441,1447,1455,1468,1481,1490,1499,1503,1507,1513,1519,1525,1537,1544,1547,1550,1561,1568,1574,1583,1594,1600,1600,1604,1611,1616,1619,1625,1628,1630,1634,1638,1646,1650,1665,1671,1675,1677,1680,1687,1698,1710,1714,1720,1728,1733,1738,1748,1756,1770,1776,1788,1795,1799,1806,1812,1817,1824,1836,1851,1863,1871,1885,1888,1895,1903,1920,1933,1953,1965,1981,1988,1996,2015,2036,2065,2096,2110,2126,2152,2193,2225,2252,2306,2319,2359,2398,2445,2478,2513,2554,2575,2601,2649,2702,2755,2791,2840,2878,2917,2965,3012,3069,3122,3186,3234,3325,3325,3383,3442,3492,3541,3572,3621,3680,3756,3821,3886,3963,4021,4067,4115,4179,4276,4340,4420,4476,4525,4583,4687,4779,4873,4981,5064,5120,5194,5298,5388,5501,5597,5688,5753,5833,5952,6072,6176,6282,6376,6428,6511,6605,6726,6804,6866,6932,6970,7042,7144,7223,7299,7365,7443,7493,7549,7603,7672,7746,7826,7867,7897,7948,8013,8076,8143,8198,8238,8263,8308,8366,8419,8461,8522,8573,8594,8632,8689,8725,8764,8798,8817,8836,8869,8923,8944,8971,9004,9035,9065,9082,9127,9176,9194,9216,9223,9236,9255,9277,9313,9338,9365,9391,9409,9433,9477,9511,9546,9592,9631,9649,9679,9718,9773,9815,9872,9926,9977,10012,10075,10125,10204,10243,10325,10387,10436,10487,10547,10612,10760,10845,10906,10981,11095,11199,11302,11383,11476,11524,11640,11862,11957,12065,12173,12261,12322,12407,12512,12627,12738,12840,12931,12980,13060,13161,13273,13385,13471,13527,13585,13660,13759,13855,13926,13990,14042,14042,14137,14204,14282,14331,14378,14406,14426,14461,14504,14563,14605,14636,14665,14675,14713,14743,14784,14808,14833,14842,14847,14867,14889,14903,14920,14940,14951,14957,14960,14978,14998,15020,15029,15046,15049,15062,15082,15102,15108,15116,15124,15128,15140,15152,15161,15175,15184,15193,15198,15209,15219,15233,15241,15261,15275,15284,15296,15315,15335,15359,15384,15401,15411,15439,15486,15515]},{"name":"新增确诊","data":[9,12,27,12,12,8,22,24,20,9,15,14,16,33,31,59,47,30,59,56,53,36,62,62,17,45,41,39,52,39,46,38,72,101,94,123,199,169,105,234,277,283,346,367,360,360,366,508,574,638,738,502,290,498,532,574,554,585,373,347,425,442,449,391,370,210,172,282,224,188,266,266,328,202,121,103,96,88,114,70,45,81,72,83,50,57,27,30,27,39,85,25,26,42,21,30,34,63,74,44,35,37,51,31,47,40,46,38,21,45,38,41,57,50,75,72,44,44,70,57,65,56,45,52,96,82,105,92,113,109,138,126,195,239,273,220,176,211,204,354,412,402,410,261,331,425,637,590,681,509,419,632,794,930,784,798,874,593,995,1230,1335,1557,1559,1330,957,1243,1349,1482,1603,1575,1353,929,698,981,1177,1359,1232,1021,640,907,1087,1185,1033,980,744,493,717,897,866,875,850,600,428,635,592,662,589,591,452,284,512,504,689,662,646,440,265,532,550,529,532,600,478,311,331,214,476,577,637,479,298,532,574,646,539,577,400,284,500,510,617,612,680,437,278,500,549,708,641,620,432,314,482,619,614,747,725,498,399,645,733,809,773,876,615,480,865,623,1046,1139,1336,946,777,1336,1548,1644,1710,1743,1441,950,1684,2208,2388,2416,2593,2176,1518,1211,1940,2502,2530,2684,2066,1434,2016,2438,2508,2447,2506,2025,1520,2156,2813,2985,2791,3035,2388,1675,2427,2986,3217,2822,2989,2502,1800,2669,3267,3739,3830,3877,5336,5,3604,3848,4528,3248,3053,3160,3319,4901,6006,7566,7879,7779,6089,4886,4531,5872,6587,7145,7013,5759,4921,5315,5529,5667,5045,4712,3990,2762,3847,3968,4127,3531,3345,2672,1788,2324,2629,2573,2372,2277,1624,1213,1570,1886,1690,1298,1363,1363,1801,1304,1447,1538,1301,1232,1032,775,1082,919,1077,1056,1213,998,697,887,1243,1170,1145,1054,1065,599,1126,1312,1279,1309,1317,989,694,1133,1533,1499,1461,1515,1118,821,1490,1925,1914,2025,2072,1784,1337,2092,2843,2606,2758,2773,2470,1571,2640,3462,3442,3532,3691,2782,2099,3709,4310,4573,4531,4786,4093,2902,4350,5296,5493,5108,5603,4605,3319,4954,5785,5897,4694,5986,5897,4468,4199,4070,4359,6053,7247,6480,4937,6237,7051,6865,6258,6421,5260,3674,5222,5818,5717,5250,5039,4046,2670,3891,4529,4138,3704,3592,2876,1789,2641,3033,2825,2595,2651,2021,1274,1883,2238,2043,1929,1943,0,2318,1418,1705,1552,1618,1518,1307,868,1411,1777,1670,1707,1631,1282,1000,1378,1820,1752,1771,1881,1485,1029,1666,2190,2246,2276,2456,2031,1504,2385,3194,3413,3431,3886,3102,2328,3758,4943,5393,4222,3574,5020,4690,7627,9574,10696,10741,12340,10176,8389,12016,14206,15259,15642,15749,14407,12071,10570,15808,18850,20364,20147,17830,14847,19950,23911]}]}}]});
印度.txt
jsonp_1629350745930_63180({"status":0,"msg":"success","data":[{"name":"印度","trend":{"updateDate":["4.7","4.8","4.9","4.10","4.11","4.12","4.13","4.14","4.15","4.16","4.17","4.18","4.19","4.20","4.21","4.22","4.23","4.24","4.25","4.26","4.27","4.28","4.29","4.30","5.1","5.2","5.3","5.4","5.5","5.6","5.7","5.8","5.9","5.10","5.11","5.12","5.13","5.14","5.15","5.16","5.17","5.18","5.19","5.20","5.21","5.22","5.23","5.24","5.25","5.26","5.27","5.28","5.29","5.30","5.31","6.1","6.2","6.3","6.4","6.5","6.6","6.7","6.8","6.9","6.10","6.11","6.12","6.13","6.14","6.15","6.16","6.17","6.18","6.19","6.20","6.21","6.22","6.23","6.24","6.25","6.26","6.27","6.28","6.29","6.30","7.1","7.2","7.3","7.4","7.5","7.6","7.7","7.8","7.9","7.10","7.11","7.12","7.13","7.14","7.15","7.16","7.17","7.18","7.19","7.20","7.21","7.22","7.23","7.24","7.25","7.26","7.27","7.28","7.29","7.30","7.31","8.1","8.2","8.3","8.4","8.5","8.6","8.7","8.8","8.9","8.10","8.11","8.12","8.13","8.14","8.15","8.16","8.17","8.18","8.19","8.20","8.21","8.22","8.23","8.24","8.25","8.26","8.27","8.28","8.29","8.30","8.31","9.1","9.2","9.3","9.4","9.5","9.6","9.7","9.8","9.9","9.10","9.11","9.12","9.13","9.14","9.15","9.16","9.17","9.18","9.19","9.20","9.21","9.22","9.23","9.24","9.25","9.26","9.27","9.28","9.29","9.30","10.1","10.2","10.3","10.4","10.5","10.6","10.7","10.8","10.9","10.10","10.11","10.12","10.13","10.14","10.15","10.16","10.17","10.18","10.19","10.20","10.21","10.22","10.23","10.24","10.25","10.26","10.27","10.28","10.29","10.30","10.31","11.1","11.2","11.3","11.4","11.5","11.6","11.7","11.8","11.9","11.10","11.11","11.12","11.13","11.14","11.15","11.16","11.17","11.18","11.19","11.20","11.21","11.22","11.23","11.24","11.25","11.26","11.27","11.28","11.29","11.30","12.1","12.2","12.3","12.4","12.5","12.6","12.7","12.8","12.9","12.10","12.11","12.12","12.13","12.14","12.15","12.16","12.17","12.18","12.19","12.20","12.21","12.22","12.23","12.24","12.25","12.26","12.27","12.28","12.29","12.30","12.31","1.1","1.2","1.3","1.4","1.5","1.6","1.7","1.8","1.9","1.10","1.11","1.12","1.13","1.14","1.15","1.16","1.17","1.18","1.19","1.20","1.21","1.22","1.23","1.24","1.25","1.26","1.27","1.28","1.29","1.30","1.31","2.1","2.2","2.3","2.4","2.5","2.6","2.7","2.8","2.9","2.10","2.11","2.12","2.13","2.14","2.15","2.16","2.17","2.18","2.19","2.20","2.21","2.22","2.23","2.24","2.25","2.26","2.27","2.28","3.1","3.2","3.3","3.4","3.5","3.6","3.7","3.8","3.9","3.10","3.11","3.12","3.13","3.14","3.15","3.16","3.17","3.18","3.19","3.20","3.21","3.22","3.23","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","4.1","4.2","4.3","4.4","4.5","4.6","4.7","4.8","4.9","4.10","4.11","4.12","4.13","4.14","4.15","4.16","4.17","4.18","4.19","4.20","4.21","4.22","4.23","4.24","4.25","4.26","4.27","4.28","4.29","4.30","5.1","5.2","5.3","5.4","5.5","5.6","5.7","5.8","5.9","5.10","5.11","5.12","5.13","5.14","5.15","5.16","5.17","5.18","5.19","5.20","5.21","5.22","5.23","5.24","5.25","5.26","5.27","5.28","5.29","5.30","5.31","6.1","6.2","6.3","6.4","6.5","6.6","6.7","6.8","6.9","6.10","6.11","6.12","6.13","6.14","6.15","6.16","6.17","6.18","6.19","6.20","6.21","6.22","6.23","6.24","6.25","6.26","6.27","6.28","6.29","6.30","7.1","7.2","7.3","7.4","7.5","7.6","7.7","7.8","7.9","7.10","7.11","7.12","7.13","7.14","7.15","7.16","7.17","7.18","7.19","7.20","7.21","7.22","7.23","7.24","7.25","7.26","7.27","7.28","7.29","7.30","7.31","8.1","8.2","8.3","8.4","8.5","8.6","8.7","8.8","8.9","8.10","8.11","8.12","8.13","8.14","8.15","8.16","8.17","8.18"],"list":[{"name":"确诊","data":[5480,5916,6725,7600,8446,9205,10453,11487,12322,13430,14352,15722,17615,18539,20080,21370,23039,24447,26283,27890,29451,31332,33062,34862,37257,39699,42505,46437,49400,52987,56351,59693,62808,67161,70768,74243,78055,81997,85784,90648,95698,100161,103292,107819,114478,124073,130506,137608,141228,150313,154820,163120,172359,180621,189765,194837,202860,214664,224215,233576,243733,254340,264143,273443,284754,297001,305951,317368,324482,336185,347821,359506,371734,385276,400724,421765,430708,449613,465553,481179,501864,527738,548154,562457,574926,593703,612486,633381,664488,687760,712920,739646,760761,790649,818647,847575,871499,898680,933450,959993,1001863,1036497,1055932,1106135,1127281,1171446,1220433,1263336,1323471,1383172,1424202,1466059,1529653,1579240,1601070,1690546,1749771,1780268,1830949,1901334,1958592,2021407,2057816,2129154,2199101,2244435,2322755,2372318,2431558,2506247,2530943,2634256,2684314,2732218,2814157,2873173,2925337,3038013,3079925,3149759,3211848,3286512,3377908,3454513,3477250,3583807,3649639,3715931,3810625,3904508,3993412,4092550,4160493,4236961,4313129,4417550,4494389,4606149,4688470,4788593,4878042,4963097,5060818,5141905,5228478,5323907,5417274,5517601,5580286,5669610,5765744,5843349,5915753,6041638,6087454,6156722,6245404,6323247,6438968,6509916,6573678,6650456,6724380,6764710,6841813,6946598,6997852,7063955,7160805,7205923,7275588,7349290,7416538,7475572,7536769,7574167,7644979,7701365,7727289,7781746,7829226,7873664,7918102,7974963,8006340,8070589,8094636,8178645,8208774,8250951,8305267,8352518,8380734,8439389,8478689,8531420,8576689,8601937,8659513,8690621,8751254,8790760,8837037,8867857,8886987,8925467,8974910,9021020,9065301,9129003,9170825,9193982,9245108,9291068,9308751,9393039,9432075,9463254,9484506,9523678,9556881,9593688,9625289,9667084,9689302,9714308,9756610,9780486,9814064,9844322,9881357,9902262,9925062,9933997,9966966,9987949,10015973,10047131,10067196,10094801,10111256,10141215,10157903,10178592,10208725,10224797,10237117,10260618,10282624,10293028,10310778,10337069,10345118,10369514,10388018,10405097,10426407,10448134,10460179,10473696,10485420,10497470,10525452,10540365,10556184,10566720,10572672,10582647,10606215,10619603,10634414,10645580,10661138,10672035,10689202,10690279,10702730,10720971,10740309,10750224,10764177,10768991,10788136,10799024,10805790,10816147,10831279,10846028,10848045,10859057,10878758,10880794,10894638,10910589,10919616,10931492,10942948,10956182,10969230,10989668,10997821,11008665,11028114,11043925,11056933,11077957,11094249,11102946,11121186,11136452,11152127,11171166,11190651,11204179,11228288,11241990,11260750,11266216,11287543,11327129,11353712,11382610,11404279,11410769,11473015,11509345,11551980,11590373,11607548,11682440,11726364,11780157,11794407,11860672,11965931,11990353,12089876,12110693,12203953,12229790,12319836,12476468,12508609,12625146,12732968,12847674,12978132,13164235,13261376,13444844,13564561,13714419,13960574,14268441,14465797,14732074,15040130,15239230,15609004,15924806,16257309,16519812,16869825,17116637,17519369,17867648,18368096,18754984,19157094,19549656,19919715,20275543,20658234,21070852,21485285,21886611,22295911,22662410,22991927,23340426,23702832,24046120,24372243,24683065,24964925,25227970,25495144,25771405,26030674,26285069,26528846,26751681,26947496,27156382,27367935,27547705,27719431,27893472,28046957,28173655,28306883,28440988,28572359,28693835,28808372,28909604,28996949,29088176,29182072,29273338,29358033,29424006,29507438,29570035,29632261,29699555,29761964,29822764,29881352,29934361,29973457,30027850,30082169,30133417,30182469,30232320,30278963,30316000,30361699,30410577,30453937,30501189,30544485,30584872,30618939,30662896,30708570,30743013,30794756,30836231,30873907,30904734,30944949,30986803,31025875,31063987,31105270,31141669,31153392,31209914,31219374,31289115,31297122,31341507,31396300,31417313,31470893,31490153,31528114,31579651,31619573,31693625,31708870,31732703,31809049,31815756,31884819,31902422,31944077,31981869,31998158,32052127,32077706,32117826,32190846,32205973,32249573,32279653,32295224]},{"name":"治愈","data":[468,506,620,774,969,1080,1181,1359,1432,1768,2041,2463,2854,3273,3975,4370,5012,5496,5939,6523,7137,7796,8437,9068,10007,10819,11775,12847,14142,15331,16776,17887,19301,20696,22549,24420,26400,27969,30234,34224,36795,38909,40458,43070,46002,50857,53947,54865,58727,63536,65944,69534,81606,84759,91016,93343,98113,103641,107419,112189,117404,122738,127991,131775,140033,146074,152395,159597,164803,172313,184243,190755,196894,208169,216730,235078,240289,254204,264542,277765,292626,308928,321178,329728,340225,353333,366027,383936,404351,417509,435441,454858,470144,483348,513503,532532,546379,566664,590219,609831,620194,651308,664461,693450,707523,737808,772488,800158,841424,883977,910298,936171,987174,1017204,1029069,1091018,1144277,1165442,1200303,1278084,1298528,1374420,1402076,1461772,1506413,1560800,1633356,1673885,1725834,1770682,1810079,1904612,1939454,2005215,2075836,2129764,2175492,2273973,2310922,2355823,2445975,2506724,2577990,2640121,2658419,2744887,2800671,2856147,2931005,3014685,3086545,3162305,3219750,3278999,3352316,3433604,3490908,3586216,3648534,3730949,3809549,3887371,3976413,4039986,4125742,4221471,4313402,4432630,4509924,4609704,4700625,4779658,4852313,4981099,5025815,5109584,5206044,5280204,5393737,5466344,5527934,5621193,5703607,5750403,5836826,5946371,6003244,6087588,6203130,6255622,6343270,6425716,6505179,6571659,6642698,6693491,6784742,6867988,6903365,6965699,7030903,7085242,7141966,7234749,7273649,7348147,7376961,7481951,7511472,7570044,7644926,7697460,7733477,7791363,7837061,7891991,7941094,7969954,8037467,8070817,8138948,8180967,8233765,8279822,8303358,8346331,8400113,8443553,8491462,8550931,8592303,8618445,8661421,8700681,8716566,8801161,8846313,8889585,8915158,8958524,8998066,9042308,9079888,9126233,9156423,9189704,9238188,9268492,9309031,9343056,9383735,9415086,9444229,9456552,9507421,9530530,9564162,9595711,9621683,9656883,9674090,9709469,9728747,9750670,9782669,9806767,9821119,9850394,9876557,9889946,9910982,9939466,9952548,9986904,10009404,10026751,10048922,10072016,10084011,10100053,10114980,10130451,10157879,10173747,10192158,10204340,10211342,10228753,10256410,10273553,10291077,10306666,10321966,10334850,10356476,10359305,10373649,10394352,10415080,10424619,10442137,10449858,10475872,10487650,10497654,10510807,10525343,10544069,10547201,10560593,10579622,10589230,10600905,10613072,10624838,10637743,10648633,10658469,10672253,10686299,10694193,10703460,10723130,10734328,10741483,10760379,10771400,10779954,10794590,10807877,10818721,10836798,10851094,10860512,10880059,10893442,10916916,10923264,10938146,10966735,10982516,11003784,11018816,11027543,11060390,11079697,11103681,11124465,11134333,11176854,11198515,11226705,11232919,11270831,11320418,11332289,11387270,11401824,11462934,11475836,11532137,11625318,11639575,11698657,11753169,11809277,11867486,11964985,12008162,12109473,12165126,12263113,12362012,12530565,12633314,12774046,12930733,13052362,13221039,13312271,13593113,13804309,14018818,14150962,14468946,14695983,14923460,15305026,15498680,15885993,16240047,16455477,16875349,17000610,17407470,17719749,18234220,18591134,18970018,19328365,19611259,19844129,20281508,20679456,21039370,21492926,21754130,22277260,22665206,23022025,23383307,23693992,23948435,24278735,24604894,24693493,25037378,25227740,25647332,25917521,25994295,26198172,26428307,26724010,26916989,27008777,27282022,27479472,27629621,27756262,27865723,27957446,28105369,28231022,28345261,28454938,28558214,28627998,28725030,28830037,28911454,28950726,29034224,29064502,29132853,29238048,29293497,29317068,29416815,29456404,29519131,29548302,29632032,29682688,29723553,29769484,29799534,29863463,29901927,29957090,30000214,30050975,30063720,30129597,30157396,30191151,30239521,30297377,30313050,30374508,30390687,30454757,30468079,30504747,30555315,30579106,30634202,30663147,30701612,30743972,30781263,30846509,30869454,30896354,30965030,30974748,31037245,31055861,31102724,31148536,31180968,31230332,31260050,31302345,31365316,31381493,31440221,31470067,31492285]},{"name":"死亡","data":[164,178,226,249,288,331,358,393,405,448,486,521,559,592,645,681,721,780,825,882,939,1008,1079,1154,1223,1323,1391,1566,1693,1785,1889,1985,2101,2212,2294,2415,2551,2649,2753,2871,3025,3144,3179,3317,3465,3707,3850,4004,4057,4334,4406,4653,4956,5144,5390,5577,5679,6028,6301,6440,6845,7117,7449,7558,7996,8473,8718,9109,9247,9590,10015,12029,12360,12677,13035,13502,13780,14162,14634,15042,15487,16088,16466,16797,17038,17521,17996,18320,18953,19568,20073,20618,21072,21586,22122,22659,23078,23569,24281,24865,25589,26267,26508,27428,27628,28488,29531,30122,31112,32082,32656,33129,34223,34948,35134,36497,37390,37690,38485,39787,40722,41627,42026,43144,44048,44855,46062,46717,47527,48888,49171,50845,51685,52280,53701,54438,55174,56792,57258,58317,59305,60267,61646,62669,62837,64062,64951,65725,66871,68059,69214,70519,71120,72033,73105,74367,75328,76744,77768,78931,80026,81168,82504,83433,84505,85731,86909,88231,89117,90282,91435,92587,93461,94971,95678,96468,97761,98822,100323,101211,101997,103005,104032,104651,105632,106925,107568,108412,109667,110118,110966,111726,112862,113578,114511,114902,115879,116585,117011,117474,118236,118621,119148,119823,120179,120899,121211,122099,122424,122848,123454,123955,124552,125263,125895,126370,126864,127170,127810,128204,128894,129357,129969,130391,130670,131130,131770,132310,132872,133589,134088,134383,134989,135533,135734,136733,137177,137659,137933,138467,138946,139473,139962,140481,140782,141078,141668,141977,142417,142841,143352,143667,143985,144144,144662,144914,145322,145669,146025,146414,146562,147029,147241,147521,147940,148190,148329,148660,148950,149095,149305,149603,149721,150028,150272,150470,150752,151000,151149,151265,151389,151578,151910,152068,152272,152369,152456,152593,152802,152947,153104,153316,153462,153525,153722,153751,153895,154047,154202,154358,154472,154547,154690,154782,154884,154966,155078,155158,155196,155286,155443,155489,155609,155734,155789,155883,155977,156090,156181,156325,156376,156457,156581,156713,156820,156947,157060,157125,157242,157360,157447,157562,157689,157750,157875,157949,158075,158123,158236,158418,158596,158750,158836,158902,159246,159387,159578,159728,159834,160181,160427,160642,160761,161049,161562,161730,162110,162237,162818,162993,163485,164610,164745,165293,165851,166426,167105,168203,168690,169651,170377,171205,172461,174171,175238,176745,178557,179795,181870,183088,186184,188630,191281,193055,196609,199388,202281,207215,209581,213997,218124,220571,225037,226720,231419,235189,242029,245057,249183,253470,256940,259479,264124,268521,273038,276947,279919,286063,290795,295047,298761,303355,305848,310416,314908,315869,320264,322982,328871,331607,332644,335489,338400,342280,346055,347259,350631,353246,355374,361010,364113,367577,371271,375185,377061,379601,382785,384275,385815,388096,389258,389661,391385,392123,393508,395715,396631,396972,398456,398913,399872,400434,401538,402359,403085,403700,404341,405425,406200,407537,408763,409267,409338,411928,412204,412720,413305,414113,414338,414657,418623,419471,419613,420196,420758,421117,421712,422175,422695,423403,423965,424777,425082,425388,426294,426434,427149,427565,428072,428577,428715,429564,429702,430285,431240,431558,432110,432421,432834]},{"name":"新增确诊","data":[533,565,809,875,846,759,1248,1034,835,1060,922,1370,1250,924,1541,1290,1669,1408,1836,1607,1561,1873,1738,1800,2394,2442,2806,3932,2963,3587,3364,3342,3113,4353,3607,3475,3763,3942,3787,4864,5050,4463,3131,4527,6659,9595,6433,7102,3620,9085,4507,8300,9239,8262,9144,5072,8023,11804,9551,9361,10157,10607,9803,9300,11311,12247,8950,11417,7114,11703,11636,11685,12228,13542,15448,21041,8943,18905,15940,15626,20685,25874,20416,14303,12469,18777,18783,20895,31107,23272,25160,26726,21115,29888,27998,28928,23924,27181,34770,26543,41870,34634,37407,50203,36810,44165,48987,42903,60135,59701,41030,41857,63594,49587,54966,57704,59225,52783,50681,70385,57258,62815,61455,71338,69947,45334,78320,49563,59240,74689,24696,103313,50058,47904,81939,59016,52164,112676,41912,69834,62089,74664,91396,76605,22737,106557,65832,66292,94694,93883,88904,99138,67943,76468,76168,104421,76839,111760,82321,100123,89449,85055,97721,81087,86573,95429,93367,100327,62685,89324,96134,77605,72404,125885,45816,69268,88682,77843,115721,70948,63762,76778,73924,40330,77103,104785,51254,66103,96850,45118,69665,73702,67248,59034,61197,37398,70812,56386,25924,54457,47480,44438,44438,56861,31377,64249,24047,84009,30129,42177,54316,47251,28216,58655,39300,52731,45269,25248,57576,31108,60633,39506,46277,30820,19130,38480,49443,46110,44281,63702,41822,23157,51126,45960,17683,84288,39036,42098,21252,39172,33203,36807,31601,41795,22218,25006,42302,23876,33578,30258,37035,20905,22800,8935,32969,20983,28024,31158,20065,27605,16455,29959,16688,20689,30133,16072,12320,23501,22006,10404,17750,26291,8049,24396,18504,17079,21310,21727,12045,13517,11724,12050,27982,14913,15819,10536,5952,9975,23568,13388,14811,11166,15558,10897,17167,1077,12451,18241,19338,9915,13953,4814,19145,10888,6766,10357,15132,14749,2017,11012,19701,2036,13844,15951,9027,11876,11456,13234,13048,20438,8153,10844,19449,15811,13008,21024,16292,8697,18240,15266,15675,19039,19485,13528,24109,13702,18760,5466,21327,39586,26583,28898,21669,6490,62246,36330,42635,38393,17175,74892,43924,53793,14250,66265,105259,24422,99523,20817,93260,25837,90046,156632,32141,116537,107822,114706,130458,186103,97141,183468,119717,149858,246155,307867,197356,266277,308056,199100,288956,315802,332503,326769,350013,246812,402732,348279,307219,386888,402110,392562,370059,355828,382691,412618,414433,401326,409300,366499,329517,348499,362406,343288,326123,310822,281860,263045,267174,276261,259269,254395,243777,222835,195815,208886,211553,179770,171726,174041,153485,126698,133228,134105,131371,121476,114537,101232,87345,91227,93896,91266,84695,65973,68400,62597,62226,67294,62409,60800,58588,53009,39096,54393,54319,51248,49052,49851,46643,37037,45699,48878,43360,47252,43296,40387,34067,43957,45674,34443,42648,41475,37676,30827,40215,67344,39072,38112,41283,36399,11723,56522,9460,69741,8007,44385,54793,21013,53580,19260,37961,51537,39922,74052,15245,23833,76346,6707,69063,17603,41655,37792,16289,53969,25579,40120,73020,15127,43600,30080,15571]}]}}]});
5、创建折线图
import json
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LabelOpts
# 处理数据
f_us = open("..\折线图数据\美国.txt", "r", encoding="utf-8")
us_data =f_us.read()
f_jp = open("..\折线图数据\日本.txt", "r", encoding="utf-8")
jp_data =f_jp.read()
f_in = open("..\折线图数据\印度.txt", "r", encoding="utf-8")
in_data =f_in.read()
# 去掉无用的开头
us_data = us_data.replace("jsonp_1629344292311_69436(", "")
jp_data = jp_data.replace("jsonp_1629350871167_29498(", "")
in_data = in_data.replace("jsonp_1629350745930_63180(", "")
# 去掉无用的尾部 );
us_data = us_data[:-2]
jp_data = jp_data[:-2]
in_data = in_data[:-2]
# 把json类型转换为 python数据类型
us_data = json.loads(us_data)
jp_data = json.loads(jp_data)
in_data = json.loads(in_data)
us_trend_data = us_data["data"][0]["trend"]
jp_trend_data = jp_data["data"][0]["trend"]
in_trend_data = in_data["data"][0]["trend"]
# 获取日期数据,作为x轴数据
us_x_data = us_trend_data["updateDate"]
jp_x_data = jp_trend_data["updateDate"]
in_x_data = in_trend_data["updateDate"]
us_x_data = us_x_data[:314]
jp_x_data = jp_x_data[:314]
in_x_data = in_x_data[:314]
# 获取 确诊数据 ,作为y轴数据
us_y_data = us_trend_data["list"][0]["data"]
jp_y_data = jp_trend_data["list"][0]["data"]
in_y_data = in_trend_data["list"][0]["data"]
us_y_data = us_y_data[:314]
jp_y_data = jp_y_data[:314]
in_y_data = in_y_data[:314]
# 生成折线图
line = Line()
# 添加x轴数据,x轴数据是一样的,美国 日本 印度 选一个就行
line.add_xaxis(us_x_data)
# 添加y轴数据
# 给y轴数据设置series_name 当鼠标移到对应折线上就会显示,容易区分折线是哪个国家的
# 为y轴元素设置属性 label_opts=LabelOpts(is_show=False) 这样在折线图上就不会展示数字了,因为折线之间的数字会互相覆盖,显得很乱
line.add_yaxis("美国确诊人数", us_y_data, label_opts=LabelOpts(is_show=False))
line.add_yaxis("日本确诊人数", jp_y_data, label_opts=LabelOpts(is_show=False))
line.add_yaxis("印度确诊人数", in_y_data, label_opts=LabelOpts(is_show=False))
# 设置全局配置项
line.set_global_opts(
title_opts=TitleOpts(title="2020年美日印肺炎确诊人数对比折线图", pos_left="center", pos_bottom="1%")
)
# 生成render 图表
line.render()
# 关闭文件数据连接
f_us.close()
f_jp.close()
f_in.close()
给y轴数据设置series_name 当鼠标移到对应折线上就会显示,容易区分折线是哪个国家的
为y轴元素设置属性 label_opts=LabelOpts(is_show=False) 这样在折线图上就不会展示数字了,因为折线之间的数字会互相覆盖,显得很乱
9.3.2 疫情地图绘制
1、基础地图使用
# 基础地图绘制
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts, TitleOpts, TooltipOpts, LabelOpts
# 准备地图对象
map = Map()
# 准备数据
data = [
("北京市", 99),
("上海市", 199),
("湖南省", 299),
("台湾省", 199),
("广东省", 599)
]
# 添加数据
map.add("测试地图", data, "china")
# 设置全局选项
map.set_global_opts(
# title_opts=TitleOpts(title="测试地图", pos_left="center", pos_bottom="1%"),
visualmap_opts=VisualMapOpts(
is_show=True,
is_piecewise=True,
pieces=[
{"min": 1, "max": 9, "label": "1-9人", "color": "#CCFFFF"},
{"min": 10, "max": 99, "label": "10-99人", "color": "#FFFF99"},
{"min": 100, "max": 499, "label": "100-499人", "color": "#FF9966"},
{"min": 500, "max": 999, "label": "500-999人", "color": "#FF6666"},
{"min": 1000, "max": 9999, "label": "1000-9999人", "color": "#FF3333"},
{"min": 10000, "label": "10000以上", "color": "#990033"},
]
)
)
# 绘制地图
map.render()
色值设置:网页设计常用色彩搭配表 | 网页配色表
2、全国疫情地图
# 绘制全国疫情地图
import json
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts, TitleOpts
# 1-数据获取
# 打开数据文件
f = open("..\地图数据\疫情.txt", "r", encoding="utf-8")
# 读取文件内容
f_data = f.read()
# 关闭文件连接
f.close()
# 2-数据处理
# 把json数据转换为python的数据类型
data = json.loads(f_data)
#获取全部省份的疫情数据
data = data["areaTree"][0]["children"]
# print(data)
# 定义一个新列表接收处理好的省份和对应省份确诊人数
final_data = []
for element in data:
name = element["name"]
if name in ['上海', '天津', '北京', '重庆']:
name = name + "市"
elif name in ["香港", "澳门"]:
name = name + "特别行政区"
elif name in ["西藏", "内蒙古"]:
name = name + "自治区"
elif name == "宁夏":
name = name + "回族自治区"
elif name == "广西":
name = name + "壮族自治区"
elif name == "新疆":
name = name + "维吾尔自治区"
else:
name = name + "省"
confirm = element["total"]["confirm"]
final_data.append((name, confirm))
# print(final_data)
# 3-地图绘制
# 创建地图对象
map = Map()
# 数据添加
map.add("总确诊人数", final_data, "china")
# 全局配置项设置
map.set_global_opts(
title_opts=TitleOpts(title="全国各省确诊人数汇总", pos_left="center", pos_bottom="1%"),
visualmap_opts=VisualMapOpts(
is_show=True,
is_piecewise=True,
pieces=[
{"min": 1, "max": 9, "label": "1-9人", "color": "#CCFFFF"},
{"min": 10, "max": 99, "label": "10-99人", "color": "#FFFF99"},
{"min": 100, "max": 499, "label": "100-499人", "color": "#FF9966"},
{"min": 500, "max": 999, "label": "500-999人", "color": "#FF6666"},
{"min": 1000, "max": 9999, "label": "1000-9999人", "color": "#FF3333"},
{"min": 10000, "label": "10000以上", "color": "#990033"},
]
)
)
# 绘制地图
map.render("全国疫情地图.html")
3、省级疫情地图
# 河南省疫情地图
import json
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts, TitleOpts
# 获取数据
f = open("..\地图数据\疫情.txt", "r", encoding="utf-8")
f_data = f.read()
f.close()
# 处理数据
# 把json转换为python数据类型
f_data = json.loads(f_data)
data = f_data["areaTree"][0]["children"][3]["children"]
# print(data)
# 创建一个列表接收河南省下的城市和对应确诊人数
final_data = []
for element in data:
city = element["name"]
if city == "境外输入":
continue
city = city + "市"
confirm = element["total"]["confirm"]
final_data.append((city, confirm))
# print(final_data)
# 绘制地图
# 创建地图对象
map = Map()
# 添加数据
map.add("各市确诊人数", final_data, "河南")
# 全局配置项设置
map.set_global_opts(
title_opts=TitleOpts(title="河南省疫情地图", pos_left="center", pos_bottom="1%"),
visualmap_opts=VisualMapOpts(
is_show=True,
is_piecewise=True,
pieces=[
{"min": 1, "max": 9, "label": "1-9人", "color": "#CCFFFF"},
{"min": 10, "max": 99, "label": "10-99人", "color": "#FFFF99"},
{"min": 100, "max": 499, "label": "100-499人", "color": "#FF9966"},
{"min": 500, "max": 999, "label": "500-999人", "color": "#FF6666"},
{"min": 1000, "max": 9999, "label": "1000-9999人", "color": "#FF3333"},
{"min": 10000, "label": "10000以上", "color": "#990033"},
]
)
)
# 绘制地图
map.render("河南省疫情地图.html")
9.3.3 柱状图绘制
1、基础柱状图绘制
给y轴数据设置series_name 当鼠标移到对应折线上就会显示,容易区分折线是哪个国家的
为y轴元素设置属性 label_opts=LabelOpts(is_show=False) 这样在折线图上就不会展示数字了,因为折线之间的数字会互相覆盖,显得很乱
# 创建柱状图对象
bar = Bar()
# 数据准备
# 添加x轴数据
bar.add_xaxis(["中国", "美国", "英国"])
# 添加y轴数据
bar.add_yaxis("GDP",[30, 20, 10])
# x轴 y轴反转
bar.reversal_axis()
# 绘图
bar.render("基础柱状图.html")
x轴 y轴反转后:
from pyecharts.charts import Bar
# 创建柱状图对象
from pyecharts.options import LabelOpts
bar = Bar()
# 数据准备
# 添加x轴数据
bar.add_xaxis(["中国", "美国", "英国"])
# 添加y轴数据
# 给y轴数据添加 label_opts=LabelOpts(position="right") 可以让数据放在对应数据柱的右侧
bar.add_yaxis("GDP",[30, 20, 10], label_opts=LabelOpts(position="right"))
# x轴 y轴反转
bar.reversal_axis()
# 绘图
bar.render("基础柱状图.html")
给y轴数据添加属性label_opts=LabelOpts(position="right) 可以让数据放在对应数据柱的右侧
2、基础时间线柱状图
这样随着x轴时间线的移动,y轴的柱状图就会切换
时间线柱状图的 颜色设置:
# 导入包
from pyecharts.charts import Bar, Timeline
from pyecharts.globals import ThemeType
from pyecharts.options import *
# 创建柱状图对象
bar1 = Bar()
bar1.add_xaxis(["中国", "美国", "英国"])
bar1.add_yaxis("GDP", [30, 20, 10], label_opts=LabelOpts(position="right"))
bar1.reversal_axis()
bar2 = Bar()
bar2.add_xaxis(["中国", "美国", "英国"])
bar2.add_yaxis("GDP", [50, 40, 30], label_opts=LabelOpts(position="right"))
bar2.reversal_axis()
bar3 = Bar()
bar3.add_xaxis(["中国", "美国", "英国"])
bar3.add_yaxis("GDP", [55, 45, 35], label_opts=LabelOpts(position="right"))
bar3.reversal_axis()
# 创建时间线对象 并设置时间线柱状图的主题颜色类型
timeline = Timeline({"theme": ThemeType.LIGHT})
# 给时间线对象 添加bar柱状图
timeline.add(bar1, "2021年GDP")
timeline.add(bar2, "2022年GDP")
timeline.add(bar3, "2023年GDP")
# 设置时间线自动播放
timeline.add_schema(
play_interval=1000, # 自动播放的时间间隔,单位毫秒
is_timeline_show=True, # 是否在自动播放时显示时间线
is_auto_play=True, # 是否自动播放
is_loop_play=True # 是否循环自动播放
)
# 绘制 时间线柱状图
timeline.render("基础时间线柱状图.html")
3、GDP动态柱状图绘制
需求:
import json
from pyecharts.charts import Bar, Timeline
from pyecharts.globals import ThemeType
from pyecharts.options import *
# 获取数据
f = open("..\\动态柱状图数据\\1960-2019全球GDP数据.csv", "r", encoding="gb2312")
f_data = f.readlines() # 得到一个列表
f.close()
# 处理数据
# 创建一个字典存储每年全球各国的GDP
# {
# 1960:[
# [”美国”, ”155亿“],
# [“中国“, ”146亿“],
# ....
# ],
# 1961:[
# [”美国”, ”155亿“],
# [“中国“, ”146亿“],
# ....
# ]
# ...
# }
dict_data = {}
# 删除第一行无用数据
f_data.pop(0)
for element in f_data:
# 去除每个字符串前后的空格和换行符
new_element= element.strip()
# 把字符串按照逗号切割到列表内
element_list = new_element.split(",")
year = (element_list[0]) # 年份
country = element_list[1] # 国家
gdp_num = float(element_list[2]) # gdp数据 有的gdp使用了科学计数法需要使用float()进行转换为正常的数字
item = [country, gdp_num]
try:
# 如果字典中已经存在某个年份的key 直接追加列表数据
dict_data[year].append(item)
except:
# 如果字典中没有这个年份的key 则新增一个空列表 之后在追加列表元素
dict_data[year] = []
dict_data[year].append(item)
# 创建一个时间线对象 并添加颜色主题类型
timeline = Timeline({"theme": ThemeType.LIGHT})
# 按年份排序
years_list = sorted(dict_data.keys())
print(years_list)
for year in years_list:
# 获取指定年份key对应的value 按照gdp降序排列
# sort()是直接修改原列表的排序,不会另存新列表
dict_data[year].sort(key=lambda item: item[1], reverse=True)
# 获取前8名gdp排名数据
year_datas = dict_data[year][:8]
# 获取x y轴数据list
x_list = []
y_list = []
for item in year_datas:
country = item[0]
gdp = item[1]
x_list.append(country) # x轴添加数据
y_list.append(gdp / 100000000) # y轴添加数据
# 创建柱状图对象,每一年都有一个柱状图
bar = Bar()
x_list.reverse()
y_list.reverse()
# 添加柱状图的x y轴数据
bar.add_xaxis(x_list)
# 给y轴数据设置series_name 当鼠标移到对应折线上就会显示,容易区分折线是哪个国家的
# 给y轴数据添加 label_opts=LabelOpts(position="right") 可以让数据放在对应数据柱的右侧
# 为y轴元素设置属性 label_opts = LabelOpts(is_show=False) 这样在折线图上就不会展示数字了,因为折线之间的数字会互相覆盖,显得很乱
bar.add_yaxis(f"{year}年GDP(亿)", y_list, label_opts=LabelOpts(position="right"))
# x y 轴反转
bar.reversal_axis()
# 设置每一年图表的标题
bar.set_global_opts(
title_opts=TitleOpts(title=f"{year}全球GDP前8排名")
)
# 给时间线对象添加柱状图
timeline.add(bar, year)
# 设置时间线自动播放
timeline.add_schema(
play_interval=1000, # 自动播放的时间间隔,单位毫秒
is_auto_play=True, # 是否自动播放
is_loop_play=True, # 是否循环自动播放
is_timeline_show=True # 是否在自动播放时显示时间线
)
# 绘制时间线柱状图
timeline.render("1960-2019全球GDP前8排名.html")
十、python的标准库
10.1 pathlib
10.1.1 创建目录对象
pathlib — Object-oriented filesystem paths — Python 3.11.4 documentation
from pathlib import Path
path = Path(r"D:\个人学习\技能专项学习\Mosh老师的python课程\笔记\test.py") # windows系统
path = Path("/usr/local/bin") # linux 或者mac系统
# 获取当前文件夹的路径对象
path = Path()
# 把路径对象组合在一起
path = Path() /Path("ecommerce")
path = Path() / "ecommerce" / "__init__.py"
# 获取当前用户的主目录
path = Path.home()
path = Path("ecommerce/__init__.py")
10.1.2 目录对象的相关操作
path = Path("ecommerce/__init__.py")
# 查看文件或目录是否存在
print(path.exists()) # True
# 是文件吗
print(path.is_file()) # True
# 是目录吗
print(path.is_dir()) # False
# 获取文件名(包括文件扩展名)
print(path.name) # __init__.py
from pathlib import Path
# 获取文件名(不包括文件扩展名)
print(path.stem) # __init__
# 获取文件扩展名
print(path.suffix) # .py
# 获取父级目录
print(path.parent) # ecommerce
# 基于现有传递创建新的路径对象,仅修改文件名和文件扩展名,但是这个文件并不是真实存在
path = path.with_name("file.txt")
print(path) # ecommerce\file.txt
# 获取绝对路径
print(path.absolute()) # D:\个人学习\技能专项学习\Mosh老师的python课程\笔记\ecommerce\file.txt
# 基于现有传递创建新的路径对象,仅修改文件扩展名, 这个文件也不是真实存在的
path = path.with_suffix(".java")
print(path.absolute()) # D:\个人学习\技能专项学习\Mosh老师的python课程\笔记\ecommerce\file.java
10.1.3 目录对象的使用
from pathlib import Path
path = Path("ecommerce1")
print(path.exists()) # False
path.mkdir()
print(path.exists()) # True
print(path) # ecommerce1
# 需要注意的是:如果进行path.rename("ecommerce2")后没有把结果重新赋值给path
# 则path还是ecommerce1
# 但是目录对象的名字已经替换为ecommerce2了
# 这个时候print(path.exists()) 会得到False 目录对象ecommerce1已经不存在了
# 进行path.rmdir()就会报错 因为目录对象ecommerce1已经不存在了,现在存在的是ecommerce2
# 所以改名后需要重新赋值给path
path = path.rename("ecommerce2")
print(path.exists()) # True
print(path) # ecommerce2
path.rmdir()
print(path.exists()) # False
from pathlib import Path
path = Path("ecommerce\__init__.py")
# 判断目录对象是否发存在
print(path.exists())
# 如果文件不存在就创建 path.touch()
# 如果目录对象是文件夹就用path.mkdir()
path.touch()
print(path.exists())
# 删除文件 path.unlink()
# 如果目录对象是文件夹就用path.rmdir() 但前提是这个文件夹是空的
path.unlink()
print(path.exists())
from pathlib import Path
path = Path("ecommerce\__init__.py")
# path.stat()用于在给定的路径上执行一个系统 stat 的调用,获取堆栈结果
print(path.stat())
# os.stat_result(st_mode=33206, st_ino=1125899906873216, st_dev=2282291619, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1687363247, st_mtime=1687363247, st_ctime=1687363247)
stat 结构的成员列表:
- st_mode− inode保护模式。
- st_ino- inode 节点编号。
- st_dev- inode驻留设备。
- st_nlink- 硬链接的数量。
- st_uid− 所有者的用户 ID。
- st_gid− 所有者的组 ID。
- st_size- 文件的大小,以字节为单位。
- st_atime− 最近访问的时间。
- st_mtime− 最近一次内容修改的时间。
- st_ctime− 最近元数据更改的时间。
目录对象可以作为一个迭代器,分别处理
1、path.iterdir()
使用path.iterdir()遍历此目录中的文件,只涉及第一层子目录。
from pathlib import Path
path = Path("ecommerce")
# 使用path.iterdir()遍历此目录中的文件,只涉及第一层子目录。
# 注意只在ecommerce子目录迭代,没有继续往customer和shopping目录里面递归
print(path.iterdir())
# <generator object Path.iterdir at 0x00FF5568>
for p in path.iterdir():
print(p)
# ecommerce\customer
# ecommerce\shopping
# ecommerce\__init__.py
# ecommerce\__pycache__
paths = [p for p in path.iterdir()]
print(paths)
# [WindowsPath('ecommerce/customer'), WindowsPath('ecommerce/shopping'), WindowsPath('ecommerce/__init__.py'), WindowsPath('ecommerce/__pycache__')]
paths = [p for p in path.iterdir() if p.is_dir()]
print(paths)
# [WindowsPath('ecommerce/customer'), WindowsPath('ecommerce/shopping'), WindowsPath('ecommerce/__pycache__')]
2、path.glob("匹配模式")
可以使用path.glob("匹配模式")在path子树上迭代,并生成与给定的相对模式匹配的所有现有文件(任何类型的文件,包括目录)
# path.glob("*.py")这个匹配模式只在在path的第一层子目录迭代,并生成与给定的相对模式匹配的所有现有文件(任何类型的文件,包括目录)
# 注意只在ecommerce子目录迭代,没有继续往customer和shopping目录里面递归
print(path.glob("*.py"))
# <generator object Path.glob at 0x02217CD8>
for p in path.glob("*.py"):
print(p)
# ecommerce\__init__.py
py_files = [p for p in path.glob("*.py")]
print(py_files)
# [ WindowsPath('ecommerce/__init__.py')]
# path.glob("**/*.py") 这个匹配模式就可以走到下一层目录了,进入customer和shopping目录里面进行匹配了
py_files = [p for p in path.glob("**/*.py")]
print(py_files)
# [WindowsPath('ecommerce/__init__.py'), WindowsPath('ecommerce/customer/contact.py'), WindowsPath('ecommerce/customer/__init__.py'), WindowsPath('ecommerce/shopping/sales.py'), WindowsPath('ecommerce/shopping/__init__.py')]
3、path.rglob("匹配模式")
path.rglob("*匹配模式") 递归地生成与给定的相对模式匹配的所有现有文件(任何类型的文件,包括目录),目录有几层就会深入几层去匹配。
# 使用path.rglob("*.py") 递归地生成与给定的相对模式匹配的所有现有文件(任何类型的文件,包括目录),该子树中的任何位置
# ecommerce目录有几层就会深入几层去匹配.py文件
print(path.rglob("*.py"))
# <generator object Path.rglob at 0x02357C68>
for p in path.rglob("*.py"):
print(p)
# ecommerce\__init__.py
# ecommerce\customer\contact.py
# ecommerce\customer\__init__.py
# ecommerce\shopping\sales.py
# ecommerce\shopping\__init__.py
py_files = [p for p in path.rglob("*.py")]
print(py_files)
# [WindowsPath('ecommerce/__init__.py'), WindowsPath('ecommerce/customer/contact.py'), WindowsPath('ecommerce/customer/__init__.py'), WindowsPath('ecommerce/shopping/sales.py'), WindowsPath('ecommerce/shopping/__init__.py')]