Python入门笔记(七)

embedded/2024/10/15 17:17:48/

文章目录

  • 第十五章. 下载数据
    • 15.1 csv文件
    • 15.2 json文件
  • 第十六章. 使用API
    • 16.1 requests


前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。
点击跳转:人工智能从入门到精通教程





本文电子版获取方式:
「Python入门笔记(七).pdf」,复制整段内容,打开最新版「夸克APP」即可获取。
链接:https://pan.quark.cn/s/28f5fc0cfd49


第十五章. 下载数据

15.1 csv文件

例1:分析CSV文件头
CSV文件其文件以纯文本的形式存储表格数据(数字和文本)。纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。
在这里插入图片描述
next()返回文件的下一行

python">import csv                              # 用于分析CSV文件中的数据行filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:               # 打开文件,并将结果文件对象存储在f中reader = csv.reader(f)              # 创建与该文件相关联的阅读器对象,并存储在reader中header_row = next(reader)           # 第一行print(header_row)                   # 输出显示第一行

数据太多这里剪切一部分
在这里插入图片描述
reader处理文件以逗号分隔第一行数据,并存储在列表中。

例2:打印文件头及其位置
为让文件头数据更容易理解,将列表中的每个文件头及其位置打印出来。
调用enumerate()来获取每个元素的索引及其值

python">import csv                              # 用于分析CSV文件中的数据行filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:               # 打开文件,并将结果文件对象存储在f中reader = csv.reader(f)              # 创建与该文件相关联的阅读器对象,并存储在reader中header_row = next(reader)           # 第一行for index, column_header in enumerate(header_row):  # 调用enumerate()来获取每个元素的索引及其值print(index, column_header)

这里截取一部分图
在这里插入图片描述

例3:提取并读取数据
阅读器对象从其停留的地方继续往下读取CSV文件,每次都自动返回当前所处位置的下一行,由于我们已经读取了文件头行,这个循环将从第二行开始,这行便是数据。

python">import csv                              # 用于分析CSV文件中的数据行filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:               # 打开文件,并将结果文件对象存储在f中reader = csv.reader(f)              # 创建与该文件相关联的阅读器对象,并存储在reader中header_row = next(reader)           # 第一行highs = []                          # 空列表for row in reader:                  # 遍历每行high = int(row[1])              # str转inthighs.append(high)              # 每行的第1个元素,从第0个开始print(highs)

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

例:绘制气温图表

python">import csv                              # 用于分析CSV文件中的数据行
from matplotlib import pyplot as plt    # 画图需要# 从文件中获取最高气温
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:               # 打开文件,并将结果文件对象存储在f中reader = csv.reader(f)              # 创建与该文件相关联的阅读器对象,并存储在reader中header_row = next(reader)           # 第一行highs = []                          # 空列表for row in reader:                  # 遍历每行high = int(row[1])highs.append(high)              # 每行的第1个元素,从第0个开始print(highs)# 根据数据绘制图像
fig = plt.figure(dpi=128, figsize=(10, 6))  #设置图像大小尺寸
plt.plot(highs, c='red')# 设置图形的格式
plt.title("Daily high temperatures, July 2014", fontsize=24)  # 标题
plt.xlabel('', fontsize=16)                                   # x轴
plt.ylabel("Temperature(F)", fontsize=16)                     # y轴
plt.tick_params(axis='both', which='major', labelsize=16)     # 刻度标记大小plt.show()

在这里插入图片描述


datetime模块

python">from datetime import datetimefirst_date = datetime.strptime('2014-7-1', '%Y-%m-%d')  # 第一个参数传入实参,第二个给设置的格式
print(first_date)
python">2014-07-01 00:00:00

‘%Y-’python将字符串中第一个连字符前面的部分视为四位的年份;
‘%m-’python将第二个连字符前面的部分视为表示月份的数字;
‘%d’python将字符串的最后一部分视为月份中的一天

方法strptime()可接受各种实参,并根据它们来决定如何解读时期,下表列出这些实参:

实参含义
%A星期的名称,如Monday
%B月份名,如January
%m用数字表示的月份(01~12)
%d用数字表示的月份的一天(01~31)
%Y四位的年份,如2020
%y两位的年份,如20
%H24小时制的小时数(00~23)
%I12小时制的小时数(01~12)
%pam或pm
%M分钟数(00~59)
%S秒数(00~61)

例2:在图表中添加日期

python">import csv                              # 用于分析CSV文件中的数据行
from matplotlib import pyplot as plt    # 画图需要
from datetime import datetime           # 将字符串转换为对应日期需要# 从文件中获取最高气温和日期
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:               # 打开文件,并将结果文件对象存储在f中reader = csv.reader(f)              # 创建与该文件相关联的阅读器对象,并存储在reader中header_row = next(reader)         dates, highs = [], []               # 日期,最高温度初始化为空列表for row in reader:                  # 遍历每行current_date = datetime.strptime(row[0], "%Y-%m-%d")  # 每行第零个元素dates.append(current_date)      # 添加日期high = int(row[1])              # 最高温度转化为整型highs.append(high)              # 添加温度# 根据数据绘制图像
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red')# 设置图形的格式
plt.title("Daily high temperatures, July 2014", fontsize=24)  # 标题
plt.xlabel('', fontsize=16)                                   # x轴
fig.autofmt_xdate()                                           # 绘制斜的x轴标签
plt.ylabel("Temperature(F)", fontsize=16)                     # y轴
plt.tick_params(axis='both', which='major', labelsize=16)     # 刻度标记大小plt.show()

在这里插入图片描述


例3:添加更多数据,涵盖更长的时间
这里只是换了一个数据更多的文件,改了一个标题

python">import csv                              # 用于分析CSV文件中的数据行
from matplotlib import pyplot as plt    # 画图需要
from datetime import datetime           # 将字符串转换为对应日期需要# 从文件中获取最高气温和日期
filename = 'sitka_weather_2014.csv'
with open(filename) as f:               # 打开文件,并将结果文件对象存储在f中reader = csv.reader(f)              # 创建与该文件相关联的阅读器对象,并存储在reader中header_row = next(reader)           # 第一行dates, highs = [], []               # 日期,最高温度初始化为空列表for row in reader:                  # 遍历每行current_date = datetime.strptime(row[0], "%Y-%m-%d")  # 每行第零个元素dates.append(current_date)      # 添加日期high = int(row[1])              # 最高温度转化为整型highs.append(high)              # 添加温度# 根据数据绘制图像
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red')# 设置图形的格式
plt.title("Daily high temperatures - 2014", fontsize=24)      # 标题
plt.xlabel('', fontsize=16)                                   # x轴
fig.autofmt_xdate()                                           # 绘制斜的x轴标签
plt.ylabel("Temperature(F)", fontsize=16)                     # y轴
plt.tick_params(axis='both', which='major', labelsize=16)     # 刻度标记大小plt.show()

在这里插入图片描述


例4:再绘制一个数据系列
这里多绘制了一个最低温度

python">import csv                              # 用于分析CSV文件中的数据行
from matplotlib import pyplot as plt    # 画图需要
from datetime import datetime           # 将字符串转换为对应日期需要# 从文件中获取最高气温,最低温度和日期
filename = 'sitka_weather_2014.csv'
with open(filename) as f:               # 打开文件,并将结果文件对象存储在f中reader = csv.reader(f)              # 创建与该文件相关联的阅读器对象,并存储在reader中header_row = next(reader)           # 第一行dates, highs, lows = [], [], []     # 日期,最高温度初始化为空列表for row in reader:                  # 遍历每行current_date = datetime.strptime(row[0], "%Y-%m-%d")  # 每行第零个元素dates.append(current_date)      # 添加日期high = int(row[1])              # 最高温度转化为整型highs.append(high)              # 添加温度low = int(row[3])lows.append(low)# 根据数据绘制图像
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red')
plt.plot(dates, lows, c='blue')# 设置图形的格式
plt.title("Daily high and low temperatures - 2014", fontsize=24)  # 标题
plt.xlabel('', fontsize=16)                                       # x轴
fig.autofmt_xdate()                                               # 绘制斜的x轴标签
plt.ylabel("Temperature(F)", fontsize=16)                         # y轴
plt.tick_params(axis='both', which='major', labelsize=16)         # 刻度标记大小plt.show()

在这里插入图片描述


例5:给图表区域着色

python">import csv                              # 用于分析CSV文件中的数据行
from matplotlib import pyplot as plt    # 画图需要
from datetime import datetime           # 将字符串转换为对应日期需要# 从文件中获取最高气温,最低温度和日期
filename = 'sitka_weather_2014.csv'
with open(filename) as f:               # 打开文件,并将结果文件对象存储在f中reader = csv.reader(f)              # 创建与该文件相关联的阅读器对象,并存储在reader中header_row = next(reader)           # 第一行dates, highs, lows = [], [], []     # 日期,最高温度初始化为空列表for row in reader:                  # 遍历每行current_date = datetime.strptime(row[0], "%Y-%m-%d")  # 每行第零个元素dates.append(current_date)      # 添加日期high = int(row[1])              # 最高温度转化为整型highs.append(high)              # 添加温度low = int(row[3])lows.append(low)# 根据数据绘制图像
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red', alpha=0.5)   # alpha指定颜色的透明度,使得红色和蓝色折线看起来更浅
plt.plot(dates, lows, c='blue', alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)  # 两条线之间填充蓝色,透明度0.1# 设置图形的格式
plt.title("Daily high and low temperatures - 2014", fontsize=24)  # 标题
plt.xlabel('', fontsize=16)                                       # x轴
fig.autofmt_xdate()                                               # 绘制斜的x轴标签
plt.ylabel("Temperature(F)", fontsize=16)                         # y轴
plt.tick_params(axis='both', which='major', labelsize=16)         # 刻度标记大小plt.show()

在这里插入图片描述


例6:错误检查
有些文档可能数据不全,缺失数据可能引起异常
例如换这个文档
在这里插入图片描述
这个文档数据不全
在这里插入图片描述
这里就需要修改代码,如下:

python">import csv                              # 用于分析CSV文件中的数据行
from matplotlib import pyplot as plt    # 画图需要
from datetime import datetime           # 将字符串转换为对应日期需要# 从文件中获取最高气温,最低温度和日期
filename = 'death_valley_2014.csv'
with open(filename) as f:               # 打开文件,并将结果文件对象存储在f中reader = csv.reader(f)              # 创建与该文件相关联的阅读器对象,并存储在reader中header_row = next(reader)           # 第一行dates, highs, lows = [], [], []     # 日期,最高温度初始化为空列表for row in reader:                  # 遍历每行try:current_date = datetime.strptime(row[0], "%Y-%m-%d")  # 每行第零个元素high = int(row[1])  # 最高温度转化为整型low = int(row[3])except ValueError:print(current_date, 'missing data')else:dates.append(current_date)      # 添加日期highs.append(high)              # 添加温度lows.append(low)# 根据数据绘制图像
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red', alpha=0.5)   # alpha指定颜色的透明度,使得红色和蓝色折线看起来更浅
plt.plot(dates, lows, c='blue', alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)  # 两条线之间填充蓝色,透明度0.1# 设置图形的格式
title = 'Daily high and low temperatures - 2014\nDeath Valley, CA'
plt.title(title, fontsize=20)  # 标题
plt.xlabel('', fontsize=16)                                       # x轴
fig.autofmt_xdate()                                               # 绘制斜的x轴标签
plt.ylabel("Temperature(F)", fontsize=16)                         # y轴
plt.tick_params(axis='both', which='major', labelsize=16)         # 刻度标记大小plt.show()

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


15.2 json文件

例:存

python">import jsonnumbers = [1, 3, 5, 7, 9]filename = "numbers.json"
with open(filename, 'w') as f_obj:json.dump(numbers, f_obj)

例:取

python">import jsonfilename = "numbers.json"
with open(filename) as f_obj:numbers = json.load(f_obj)print(numbers)
python">[1, 3, 5, 7, 9]

例1:从数据地址下载json文件,这里从GitHub上下载

python">from __future__ import (absolute_import, division, print_function, unicode_literals)
from urllib.request import urlopen
import json# 网址:the url
json_url = 'https://raw.githubusercontent.com/muxuezi/btc/master/btc_close_2017.json'
response = urlopen(json_url)
req = response.read()                                # 读取数据
with open('btc_close_2017_urllib.json', 'wb') as f:  # 将数据写入文件f.write(req)
file_urllib = json.loads(req)                        # 加载json格式
print(file_urllib)

下载得到的数据:
在这里插入图片描述
例2:第二种下载方法requests

python">import requests# 网址:the url
json_url = 'https://raw.githubusercontent.com/muxuezi/btc/master/btc_close_2017.json'
req = requests.get(json_url)                           # 读取数据
with open('btc_close_2017_urllib.json', 'w') as f:     # 将数据写入文件f.write(req.text)
file_requests = req.json()

例3:从下载得到的文件中提取数据

python">import json"""文件中的数据是多个字典,字典都包含相同的键,对应不同的值,这里遍历所有字典,输出每个字典里键对应的值"""
# 将数据加载到一个列表中
filename = 'btc_close_2017_urllib.json'  # 文件
with open(filename) as f:                # 打开文件btc_data = json.load(f)              # 加载文件
# 打印每一天的信息
for btc_dict in btc_data:                # 遍历字典date = btc_dict['date']              # 每个字典中都有,日期month = btc_dict['month']            # 月份week = btc_dict['week']              # 周weekday = btc_dict['weekday']        # 周末close = btc_dict['close']            # 收盘价print("{} 是 {} 月, 第 {} 周, 星期{}, 收盘价是 {} RMB".format(date, month, week, weekday, close))

数据太多,部分如下
在这里插入图片描述

例4:收盘价

python">import json
import pygal"""文件中的数据是多个字典,字典都包含相同的键,对应不同的值,这里遍历所有字典,输出每个字典里键对应的值"""
# 将数据加载到一个列表中
filename = 'btc_close_2017_urllib.json'  # 文件
with open(filename) as f:                # 打开文件btc_data = json.load(f)              # 加载文件
# 打印每一天的信息
for btc_dict in btc_data:                # 遍历字典date = btc_dict['date']              # 每个字典中都有,日期month = int(btc_dict['month'])            # 月份week = int(btc_dict['week'])              # 周weekday = btc_dict['weekday']             # 周末close = int(float(btc_dict['close']))     # 收盘价print("{} 是 {} 月, 第 {} 周, 星期{}, 收盘价是 {} RMB".format(date, month, week, weekday, close))# 创建5个列表,分别存储日期和收盘价
dates = []
months = []
weeks = []
weekdays = []
close = []
# 每一天的信息
for btc_dict in btc_data:dates.append(btc_dict['date'])months.append(int(btc_dict['month']))weeks.append(int(btc_dict['week']))weekdays.append(btc_dict['weekday'])close.append(int(float(btc_dict['close'])))line_chart = pygal.Line(x_label_rotation=20, show_minoe_x_labels=False)
line_chart.title = '收盘价($)'
line_chart.x_labels = dates
N = 20   # x轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]
line_chart.add('收盘价', close)
line_chart.render_to_file('收盘价折线图($).svg')

在这里插入图片描述
例5:收盘价对数变换折线图

python">import json
import pygal
import math
from itertools import groupby"""文件中的数据是多个字典,字典都包含相同的键,对应不同的值,这里遍历所有字典,输出每个字典里键对应的值"""
# 将数据加载到一个列表中
filename = 'btc_close_2017_urllib.json'  # 文件
with open(filename) as f:                # 打开文件btc_data = json.load(f)              # 加载文件
# 打印每一天的信息
for btc_dict in btc_data:                # 遍历字典date = btc_dict['date']              # 每个字典中都有,日期month = int(btc_dict['month'])            # 月份week = int(btc_dict['week'])              # 周weekday = btc_dict['weekday']             # 周末close = int(float(btc_dict['close']))     # 收盘价print("{} 是 {} 月, 第 {} 周, 星期{}, 收盘价是 {} RMB".format(date, month, week, weekday, close))# 创建5个列表,分别存储日期和收盘价
dates = []
months = []
weeks = []
weekdays = []
close = []
# 每一天的信息
for btc_dict in btc_data:dates.append(btc_dict['date'])months.append(int(btc_dict['month']))weeks.append(int(btc_dict['week']))weekdays.append(btc_dict['weekday'])close.append(int(float(btc_dict['close'])))"""收盘价折线图"""
line_chart = pygal.Line(x_label_rotation=20, show_minoe_x_labels=False)
line_chart.title = '收盘价($)'
line_chart.x_labels = dates
N = 20   # x轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]
line_chart.add('收盘价', close)
line_chart.render_to_file('收盘价折线图($).svg')"""收盘价对数变换折线图"""
line_chart = pygal.Line(x_label_rotation=20, show_minoe_x_labels=False)
line_chart.title = '收盘价对数变换($)'
line_chart.x_labels = dates
N = 20   # x轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]
close_log = [math.log10(_) for _ in close]    # 这里不一样
line_chart.add('log收盘价', close_log)
line_chart.render_to_file('收盘价对数变换折线图($).svg')

在这里插入图片描述
例6:收盘价周日均值和收盘价星期均值

python">import json
import pygal
import math
from itertools import groupby"""文件中的数据是多个字典,字典都包含相同的键,对应不同的值,这里遍历所有字典,输出每个字典里键对应的值"""
# 将数据加载到一个列表中
filename = 'btc_close_2017_urllib.json'  # 文件
with open(filename) as f:                # 打开文件btc_data = json.load(f)              # 加载文件
# 打印每一天的信息
for btc_dict in btc_data:                # 遍历字典date = btc_dict['date']              # 每个字典中都有,日期month = int(btc_dict['month'])            # 月份week = int(btc_dict['week'])              # 周weekday = btc_dict['weekday']             # 周末close = int(float(btc_dict['close']))     # 收盘价print("{} 是 {} 月, 第 {} 周, 星期{}, 收盘价是 {} RMB".format(date, month, week, weekday, close))# 创建5个列表,分别存储日期和收盘价
dates = []
months = []
weeks = []
weekdays = []
close = []
# 每一天的信息
for btc_dict in btc_data:dates.append(btc_dict['date'])months.append(int(btc_dict['month']))weeks.append(int(btc_dict['week']))weekdays.append(btc_dict['weekday'])close.append(int(float(btc_dict['close'])))"""收盘价折线图"""
line_chart = pygal.Line(x_label_rotation=20, show_minoe_x_labels=False)
line_chart.title = '收盘价($)'
line_chart.x_labels = dates
N = 20   # x轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]
line_chart.add('收盘价', close)
line_chart.render_to_file('收盘价折线图($).svg')"""收盘价对数变换折线图"""
line_chart = pygal.Line(x_label_rotation=20, show_minoe_x_labels=False)
line_chart.title = '收盘价对数变换($)'
line_chart.x_labels = dates
N = 20   # x轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]
close_log = [math.log10(_) for _ in close]
line_chart.add('log收盘价', close_log)
line_chart.render_to_file('收盘价对数变换折线图($).svg')def draw_line(x_data, y_data, title, y_legend):xy_map = []for x, y in groupby(sorted(zip(x_data, y_data)), key=lambda _: _[0]):y_list = [v for _, v in y]xy_map.append([x, sum(y_list) / len(y_list)])x_unique, y_mean = [*zip(*xy_map)]line_chart = pygal.Line()           # 画图line_chart.title = title            # 设置标题line_chart.x_labels = x_uniqueline_chart.add(y_legend, y_mean)    # 添加了Y轴标签line_chart.render_to_file(title+'.svg')  # 保存为.svg文件return line_chartidx_month = dates.index('2017-12-01')
line_chart_month = draw_line(months[:idx_month], close[:idx_month],'收盘价月日均值($)', '月日均值')
line_chart_monthinx_week = dates.index('2017-12-01')
line_chart_week = draw_line(weeks[:idx_month], close[1:idx_month],'收盘价周日均值($)', '周日均值')
line_chart_weekidx_week = dates.index('2017-12-11')
wd = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday', 'Sunday']
weekdays_int = [wd.index(w) + 1 for w in weekdays[1:idx_week]]
line_chart_weekday = draw_line(weekdays_int, close[1:idx_week], '收盘价星期均值($)', '星期均值')
line_chart_weekday.x_labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
line_chart_weekday.render_to_file('收盘价星期均值($).svg')
line_chart_weekday

这里图就不贴了

最后:收盘价数据仪表盘

python">import json
import pygal
import math
from itertools import groupby"""文件中的数据是多个字典,字典都包含相同的键,对应不同的值,这里遍历所有字典,输出每个字典里键对应的值"""
# 将数据加载到一个列表中
filename = 'btc_close_2017_urllib.json'  # 文件
with open(filename) as f:                # 打开文件btc_data = json.load(f)              # 加载文件
# 打印每一天的信息
for btc_dict in btc_data:                # 遍历字典date = btc_dict['date']              # 每个字典中都有,日期month = int(btc_dict['month'])            # 月份week = int(btc_dict['week'])              # 周weekday = btc_dict['weekday']             # 周末close = int(float(btc_dict['close']))     # 收盘价print("{} 是 {} 月, 第 {} 周, 星期{}, 收盘价是 {} RMB".format(date, month, week, weekday, close))# 创建5个列表,分别存储日期和收盘价
dates = []
months = []
weeks = []
weekdays = []
close = []
# 每一天的信息
for btc_dict in btc_data:dates.append(btc_dict['date'])months.append(int(btc_dict['month']))weeks.append(int(btc_dict['week']))weekdays.append(btc_dict['weekday'])close.append(int(float(btc_dict['close'])))"""收盘价折线图"""
line_chart = pygal.Line(x_label_rotation=20, show_minoe_x_labels=False)
line_chart.title = '收盘价($)'
line_chart.x_labels = dates
N = 20   # x轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]
line_chart.add('收盘价', close)
line_chart.render_to_file('收盘价折线图($).svg')"""收盘价对数变换折线图"""
line_chart = pygal.Line(x_label_rotation=20, show_minoe_x_labels=False)
line_chart.title = '收盘价对数变换($)'
line_chart.x_labels = dates
N = 20   # x轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]
close_log = [math.log10(_) for _ in close]
line_chart.add('log收盘价', close_log)
line_chart.render_to_file('收盘价对数变换折线图($).svg')def draw_line(x_data, y_data, title, y_legend):xy_map = []for x, y in groupby(sorted(zip(x_data, y_data)), key=lambda _: _[0]):y_list = [v for _, v in y]xy_map.append([x, sum(y_list) / len(y_list)])x_unique, y_mean = [*zip(*xy_map)]line_chart = pygal.Line()           # 画图line_chart.title = title            # 设置标题line_chart.x_labels = x_uniqueline_chart.add(y_legend, y_mean)    # 添加了Y轴标签line_chart.render_to_file(title+'.svg')  # 保存为.svg文件return line_chartidx_month = dates.index('2017-12-01')
line_chart_month = draw_line(months[:idx_month], close[:idx_month],'收盘价月日均值($)', '月日均值')
line_chart_monthinx_week = dates.index('2017-12-01')
line_chart_week = draw_line(weeks[:idx_month], close[1:idx_month],'收盘价周日均值($)', '周日均值')
line_chart_weekidx_week = dates.index('2017-12-11')
wd = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday', 'Sunday']
weekdays_int = [wd.index(w) + 1 for w in weekdays[1:idx_week]]
line_chart_weekday = draw_line(weekdays_int, close[1:idx_week], '收盘价星期均值($)', '星期均值')
line_chart_weekday.x_labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
line_chart_weekday.render_to_file('收盘价星期均值($).svg')
line_chart_weekdaywith open('收盘价Dashboard.html', 'w', encoding='utf8') as html_file:html_file.write('<html><head><title>收盘价Dashboard</title><meta charset="utf-8"></head><body>\n')for svg in ['收盘价折线图($).svg', '收盘价对数变换折线图($).svg', '收盘价月日均值($).svg','收盘价周日均值($).svg', '收盘价星期均值($).svg']:html_file.write('    <object type="image/svg+xml" data="{0}" height=500></object>\n'.format(svg))  # 1html_file.write('</body></html>')

相当于把上面得到的五张图放在一个HTML文件中
在这里插入图片描述


第十六章. 使用API

16.1 requests

例:找出GitHub中星级最高的python项目
1、先查看能否成功响应

python">import requests# 执行API调用并存储响应
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code:", r.status_code)  # 状态码# 将API响应存储在一个变量中
response_dict = r.json()# 处理结果
print(response_dict.keys())
python">Status code: 200
dict_keys(['total_count', 'incomplete_results', 'items'])

2、处理响应字典

python">import requests# 执行API调用并存储响应
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code:", r.status_code)  # 状态码# 将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])# 探索有关仓库的信息
repo_dicts = response_dict['items']
print("Repositories returned:", len(repo_dicts))  # 打印有多少个仓库数,也就是python项目数# 研究第一个仓库
repo_dict = repo_dicts[0]
print("\nKeys:", len(repo_dict))
for key in sorted(repo_dict.keys()):  # 排序打印print(key)

在这里插入图片描述
3、继续研究第一个项目

python"># 研究第一个仓库
repo_dict = repo_dicts[0]
print("\nSelected information about first repository:")
print("Name:", repo_dict['name'])                # 项目名字
print("Owner:", repo_dict['owner']['login'])     # 所有者
print("Stars:", repo_dict['stargazers_count'])   # 星数
print("Repository:", repo_dict['html_url'])      # 地址
print("Created:", repo_dict['created_at'])       # 创建时间
print("Updated:", repo_dict['updated_at'])       # 修改时间
print("Description:", repo_dict['description'])  # 项目描述
python">Status code: 200
Total repositories: 8901091
Repositories returned: 30Selected information about first repository:
Name: public-apis
Owner: public-apis
Stars: 213233
Repository: https://github.com/public-apis/public-apis
Created: 2016-03-20T23:49:42Z
Updated: 2022-10-28T02:38:42Z
Description: A collective list of free APIs

4、使用Pygal可视化仓库

python">import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS# 执行API调用并存储响应
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code:", r.status_code)  # 状态码# 将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])# 探索有关仓库的信息
repo_dicts = response_dict['items']names, stars = [], []
for repo_dict in repo_dicts:names.append(repo_dict['name'])stars.append(repo_dict['stargazers_count'])# 可视化
my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False) # 第二参数标签旋转,第三参数隐藏图例
chart.title = "Most-Starred Python Projects on GitHub"
chart.x_labels = nameschart.add('', stars)
chart.render_to_file('python_repos.svg')

在这里插入图片描述
5、调整图像

python"># 可视化
my_style = LS('#333366', base_style=LCS)my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000chart = pygal.Bar(my_config, style=my_style)
chart.title = "Most-Starred Python Projects on GitHub"
chart.x_labels = nameschart.add('', stars)
chart.render_to_file('python_repos.svg')

在这里插入图片描述


http://www.ppmy.cn/embedded/127977.html

相关文章

《Oracle DB备份与恢复》开篇:一切从Oracle Incarnation开始

题记&#xff1a;从本篇开始&#xff0c;我将为大家介绍Oracle DB备份与恢复。备份恢复是DBA的核心工作&#xff0c;重在实操&#xff0c;多加练习&#xff0c;模拟各种DB或实例崩溃的场景。不同于一些博主一出场就讲如何备份恢复&#xff0c;我将从备份的源头原理开始介绍。本…

Unite Shanghai 2024 技术专场 | Unity 6及未来规划:Unity引擎和服务路线图

在 2024 年 7 月 24 日的 Unite Shanghai 2024 技术专场演讲中&#xff0c;Unity 高级技术产品经理 Jeff Riesenmy 带来演讲 Unity 6 and Beyond: A Roadmap of Unity Engine and Services。作为本次 Unite 首场专题演讲&#xff0c;他介绍了 Unity 引擎的最新进展及其配套的工…

django urlconf反向解析

Django 的 URLconf 反向解析是指通过 URL 的名称&#xff08;name 参数&#xff09;来生成 URL&#xff0c;而不是在代码中硬编码 URL 路径。这种方式更加灵活&#xff0c;方便在 URL 结构发生变化时&#xff0c;只需要修改 URL 模式&#xff0c;而不必修改代码中的所有路径引用…

golang获取当天最小的时间,以DateTime的string格式返回

推荐学习文档 golang应用级os框架&#xff0c;欢迎stargolang应用级os框架使用案例&#xff0c;欢迎star案例&#xff1a;基于golang开发的一款超有个性的旅游计划app经历golang实战大纲golang优秀开发常用开源库汇总想学习更多golang知识&#xff0c;这里有免费的golang学习笔…

02.06、回文链表

02.06、[简单] 回文链表 1、题目描述 编写一个函数&#xff0c;检查输入的链表是否是回文的。 2、解题思路&#xff1a; 快慢指针找中点&#xff1a; 利用快慢指针的技巧来找到链表的中间节点。慢指针 slow 每次移动一步&#xff0c;而快指针 fast 每次移动两步。这样&…

React中useEffect钩子

副作用&#xff1a;渲染以外的操作&#xff1a;像后端获取数据、操作DOM参数&#xff1a;副作用方法、依赖&#xff08;改变时重新执行&#xff09;调用时间&#xff1a;渲染JSX之后/依赖改变 useEffect 是 React 中的一个 Hook&#xff0c;用于在函数组件中执行副作用操作。副…

selenium的IDE插件进行录制和回放并导出为python/java脚本(10)

Selenium IDE&#xff1a;Selenium Suite下的开源Web自动化测试工具&#xff0c;是Firefox或者chrome的一个插件&#xff0c;具有记录和回放功能&#xff0c;无需编程即可创建测试用例&#xff0c;并且可以将用例直接导出为可用的python/java等编程语言的脚本。 我们以chrome浏…

Flutter路由管理(二)

路由&#xff08;Route&#xff09;在移动开发中通常是指页面&#xff08;Page&#xff09;&#xff0c;这与Web开发的意义是相同的&#xff0c;Route在Andriod中通常指一个Activaty&#xff0c;在IOS中指一个ViewController&#xff0c;路由入栈&#xff08;push&#xff09;用…