本篇是观看b站黑马视频所做的笔记第一弹,为99-126节。
- import json
- from pyecharts.charts import Line
- from pyecharts.charts import Bar
- from pyecharts.options import *
- from pyecharts.globals import ThemeType
- # 1.1 将一个列表转换为json
- data = [{"name":"张大山","age":13},{"name":"小虎","age":12}]
- json_str = json.dumps(data, ensure_ascii=False)
- print(type(json_str))
-
- # 1.2 将字典转换为json
- d = {"name":"小明","addr":"芜湖"}
- json_str2 = json.dumps(d,ensure_ascii=False)
- print(type(json_str2))
- print(json_str2)
-
- # 1.3 将Json字符串转换为py数据类型
- s = '[{"name":"小花","age":12},{"name":"小纳","age":15}]'
- l = json.loads(s)
- print(type(l))
- s1 = '{"name":"小明","addr":"芜湖"}'
- l1 = json.loads(s1)
- print(type(l1))
-
- # 2.1 基础折线图
- line = Line()
- line.add_xaxis(["中国","美国","英国"])
- line.add_yaxis("GDP",[20,30,10])
- 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)
- )
- # line.render()
-
-
- # 处理数据
-
- f_us = open("D:/PyCharm/Test/YiQingData/美国.txt", "r", encoding="UTF-8")
- us_data = f_us.read() # 美国的全部内容
-
- f_jp = open("D:/PyCharm/Test/YiQingData/日本.txt", "r", encoding="UTF-8")
- jp_data = f_jp.read() # 日本的全部内容
-
- f_in = open("D:/PyCharm/Test/YiQingData/印度.txt", "r", encoding="UTF-8")
- in_data = f_in.read() # 印度的全部内容
-
- # 去掉不合JSON规范的开头
- us_data = us_data.replace("jsonp_1629344292311_69436(", "")
- jp_data = jp_data.replace("jsonp_1629350871167_29498(", "")
- in_data = in_data.replace("jsonp_1629350745930_63180(", "")
-
- # 去掉不合JSON规范的结尾
- us_data = us_data[:-2]
- jp_data = jp_data[:-2]
- in_data = in_data[:-2]
-
- # JSON转Python字典
- us_dict = json.loads(us_data)
- jp_dict = json.loads(jp_data)
- in_dict = json.loads(in_data)
-
- # 获取trend key
- us_trend_data = us_dict['data'][0]['trend']
- jp_trend_data = jp_dict['data'][0]['trend']
- in_trend_data = in_dict['data'][0]['trend']
-
- # 获取日期数据,用于x轴,取2020年(到314下标结束)
- us_x_data = us_trend_data['updateDate'][:314]
- jp_x_data = jp_trend_data['updateDate'][:314]
- in_x_data = in_trend_data['updateDate'][:314]
-
- # 获取确认数据,用于y轴,取2020年(到314下标结束)
- us_y_data = us_trend_data['list'][0]['data'][:314]
- jp_y_data = jp_trend_data['list'][0]['data'][:314]
- in_y_data = in_trend_data['list'][0]['data'][:314]
-
- # 生成图表
- line = Line() # 构建折线图对象
- # 添加x轴数据
- line.add_xaxis(us_x_data) # x轴是公用的,所以使用一个国家的数据即可
- # 添加y轴数据 label_opts=LabelOpts(is_show=False)可以把数字去掉 要不乱乱的
- line.add_yaxis("美国确诊人数", us_y_data, label_opts=LabelOpts(is_show=False)) # 添加美国的y轴数据
- line.add_yaxis("日本确诊人数", jp_y_data, label_opts=LabelOpts(is_show=False)) # 添加日本的y轴数据
- line.add_yaxis("印度确诊人数", in_y_data, label_opts=LabelOpts(is_show=False)) # 添加印度的y轴数据
-
- # 设置全局选项
- 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()
-
- # 数据分析的案例 黑马124集
- class Record:
- def __init__(self, data, order_id, money, province):
- self.data = data
- self.order_id = order_id
- self.money = money
- self.province = province
- def __str__(self):
- return f"{self.data},{self.order_id},{self.money},{self.province}"
- class FileReader:
- # 把读到的文件转换为Record对象
- def read_data(self) -> list[Record]:
- pass
- class TextFileReader(FileReader):
- def __init__(self, path):
- self.path = path
- def read_data(self) -> list[Record]:
- f = open(self.path,"r",encoding="UTF-8")
- record_list: list[Record] = []
- for line in f.readlines():
- line = line.strip()
- data_list = line.split(",")
- record = Record(data_list[0], data_list[1],int(data_list[2]),data_list[3])
- record_list.append(record)
- f.close()
- return record_list
- class JsonFileReader(FileReader):
- def __init__(self, path):
- self.path = path
-
- def read_data(self) -> list[Record]:
- f = open(self.path, "r", encoding="UTF-8")
- record_list: list[Record] = []
- for line in f.readlines():
- data_dict = json.loads(line)
- record = Record(data_dict["date"], data_dict["order_id"], int(data_dict["money"]), data_dict["province"])
- record_list.append(record)
- f.close()
- return record_list
- if __name__ == '__main__':
- text_file_reader = TextFileReader("D:/Document/黑马python资料/第13章资料/2011年1月销售数据.txt")
- list1: list[Record] = text_file_reader.read_data()
- json_file_reader = JsonFileReader("D:/Document/黑马python资料/第13章资料/2011年2月销售数据JSON.txt")
- list2: list[Record] = json_file_reader.read_data()
- # for l in list1:
- # print(l)
- # for l in list2:
- # print(l)
- data_dict = {}
- all_data: list[Record] = list1 + list2
- for record in all_data:
- if record.data in data_dict.keys():
- data_dict[record.data] += record.money
- else:
- data_dict[record.data] = record.money
- print(data_dict)
- # 可视化图标开发
- bar = Bar()
- bar.add_xaxis(list(data_dict.keys()))
- bar.add_yaxis("销售额",list(data_dict.values()),label_opts=LabelOpts(is_show=False))
- bar.set_global_opts(
- title_opts=TitleOpts(title="每日销售额")
- )
- bar.render("每日销售额柱状图.html")
-
- # 1.类的对象,类的具体案例 类的属性:变量,成员变量 类的行为:函数,成员方法
- class Student:
- name = None
- gender = None
- nationality = None
- native_place = None
- age = None
- def say_hi(self):
- print(f"Hello World, i am {self.name}")
- stu_1 = Student()
- stu_1.name = "林俊杰"
- stu_1.gender = "男"
- stu_1.nationality = "中国"
- stu_1.age = 31
- stu_1.say_hi()
- # 2.init构造方法
- class Student1:
- name = None
- gender = None
- nationality = None
- native_place = None
- age = None
- # 在类内的方法都需要加上self
- def __init__(self, name, age, gender, nationality, native_place):
- self.name = name
- self.age = age
- self.gender = gender
- self.nationality = nationality
- self.native_place = native_place
- print("这句话会随着构造方法的执行而自然执行")
- stu_2 = Student1("小蛋蛋", 13, "男", "US", "London")
- print(stu_2.name)
-
- # 3.常用的类内置方法 成为魔术方法 __lt__ 比较大小 __le__ 小于等于 __eq__
- class Student2:
- def __init__(self, name, gender):
- self.name = name
- self.gender = gender
- def __str__(self):
- return f"对象的name为{self.name},gender为{self.gender}"
- stu_3 = Student2("小康",23)
- print(str(stu_3))
- print(stu_3)
-
- # 4.封装 私有成员变量 私有成员方法 不公开的属性和方法 不能被类直接使用,可以被,类中其他方法使用
- class Phone:
- __current_voltage = None
- face_id = " 10000"
- def __keep_single_core(self):
- print("私有的成员方法")
- def call_by_single(self):
- self.__keep_single_core()
- print("类内部的方法使用了类内部的私有方法")
- phone1 = Phone()
- phone1.call_by_single()
-
- # 5.继承 calss 类名(父类名)
- # 5.1 可多继承 class 类名(父类1, 父类2, ...)
- # 5.2 父类中都有同样的属性,则继承的是先来的那个 先入为主
- # 5.3 pass可略过,补全语法
- class iPhone(Phone):
- # 复写父类的属性与方法
- face_id = " 10001"
- def call_by_5g(self):
- print("5g通话")
- print(Phone.face_id)
- # or
- print(super().face_id)
- iphoneX = iPhone()
- iphoneX.call_by_5g()
- iphoneX.call_by_single()
-
- # 6. 类型注解 3.5版本引入了类型注解 提供了数据的显式说明
- # 6.1 可以进行简单注解 也可以进行详细的注解
- # 6.2 无法一眼看出变量的类型 通常才使用注解
- # 6.3 注解是提示性的 不是强制执行的
- var_1: int = 10
- var_2: bool = True
- pho: Phone = Phone()
- my_list1: list = [1, 2, 3]
- my_set: set[int] = {1, 2, 3}
- my_tuple: tuple[str, int, bool] = ("d", 2, True)
- # 6.2 通过注释来注解
- import random
- var_3 = random.randint(1,10) # type: int
- # 6.4 函数和方法的类型注解 包括对返回值进行限定类型 都不是强制型的
- def add_xy(x: int, y: int) -> int:
- return x+y
-
- # 6.5 union注解 定义联合类型注解 针对混合类型
- from typing import Union
- my_dict1: dict[str,Union[str,int]] = {"name":"小明","age":12}
- def func_1(data: Union[int,str]) -> Union[int,str]:
- pass
-
- # 7. 多态 同样的行为 传入不同的对象 得到不同的状态
- # 7.05 父类来确定有那些方法 具体的实现 由子类自行决定
- class Animal():
- def speak(self):
- pass
- class Cat(Animal):
- def speak(self):
- print("喵喵喵")
- class Dog(Animal):
- def speak(self):
- print("汪汪汪")
- def makeNoise(animal: Animal):
- animal.speak()
- cat = Cat()
- cat.speak()
- dog = Dog()
- dog.speak()
-
- # 7.1 抽象类 含有抽象方法的类成为抽象类 抽象方法:方法体是空实现的 pass 成为抽象方法
- # 也就是上面的Animal类 是顶层设计 相当于给子类做规范