整理

上级 789a0c37
"""
演示第三个图表:GDP动态柱状图开发
"""
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType
from pyecharts import options as opts
# 读取数据
f = open("/Users/qinyingjie/Documents/python-workspace/python-demo/data/动态柱状图数据/csdn.csv", "r",
encoding="UTF-8")
data_lines = f.readlines()
# 关闭文件
f.close()
# 删除第一条数据
data_lines.pop(0)
# 将数据转换为字典存储,格式为:
# { 年份: [ [国家, gdp], [国家,gdp], ...... ], 年份: [ [国家, gdp], [国家,gdp], ...... ], ...... }
# { 1960: [ [美国, 123], [中国,321], ...... ], 1961: [ [美国, 123], [中国,321], ...... ], ...... }
# 先定义一个字典对象
data_dict = {}
bar_colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF', '#C0C0C0', '#800080']
for line in data_lines:
year = (line.split(",")[0]) # 日期
country = line.split(",")[1] # 昵称
gdp = float(line.split(",")[2]) # 红包数据
# 如何判断字典里面有没有指定的key呢?
try:
data_dict[year].append([country, gdp])
except KeyError:
data_dict[year] = []
data_dict[year].append([country, gdp])
# print(data_dict[1960])
# 创建时间线对象
timeline = Timeline({"theme": ThemeType.LIGHT})
# 排序年份
sorted_year_list = sorted(data_dict.keys())
for year in sorted_year_list:
data_dict[year].sort(key=lambda element: element[1], reverse=True)
# 取出本年份前8名的国家
year_data = data_dict[year][0:8]
x_data = []
y_data = []
for i, country_gdp in enumerate(year_data):
x_data.append(country_gdp[0]) # x轴添加国家
y_data.append(country_gdp[1]) # y轴添加gdp数据
# 构建柱状图
bar = Bar()
x_data.reverse()
y_data.reverse()
# bar.add_xaxis(x_data)
# for i, (country, gdp,color) in enumerate(zip(x_data, y_data,bar_color_list)):
# bar.add_yaxis(
# series_name=country,
# yaxis_data=[gdp],
# label_opts=opts.LabelOpts(position="right", color=bar_color_list[i]),
# )
bar.add_xaxis(x_data)
bar.add_yaxis("红包数据", y_data, label_opts=LabelOpts(position="right"))
# bar.add_yaxis("红包数据", y_data, label_opts=LabelOpts(position="right"), itemstyle_opts=ItemStyleOpts(color=bar_color_list))
# 反转x轴和y轴
bar.reversal_axis()
# 设置每一天的图表的标题
bar.set_global_opts(
title_opts=TitleOpts(title=f"{year}-CSDN抢到红包累计排名")
)
timeline.add(bar, str(year))
# for循环每一年的数据,基于每一年的数据,创建每一年的bar对象
# 在for中,将每一年的bar对象添加到时间线中
# 设置时间线自动播放
timeline.add_schema(
play_interval=2000,
is_timeline_show=True,
is_auto_play=True,
is_loop_play=False
)
# 绘图
timeline.render("2023年11月11-2023年12月15每天CSDN抢到红包累计排名前8用户.html")
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: Roc-xb
"""
import hashlib
import hmac
from base64 import b64encode
import random
import requests
# 获取x-ca-nonce
def get_nonce():
text = ""
char_list = []
for c in range(97, 97 + 6):
char_list.append(chr(c))
for c in range(49, 58):
char_list.append(chr(c))
for i in "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx":
if i == "4":
text += "4"
elif i == "-":
text += "-"
else:
text += random.choice(char_list)
return text
# 获取x-ca-signature
def get_signature(nonce):
appSecret = "OTGHZy1hLh1HFWbLnpG68OwZGc2TQwld".encode()
to_enc = f"GET\napplication/json, text/plain, */*\n\n\n\nx-ca-key:203871397\nx-ca-nonce:{nonce}\n/mp/ask/v1/questions/list?communityInfo=1&pageNo=1&pageSize=30&quick=3&rewardType=2&sortBy=1&type=5".encode()
signature = b64encode(hmac.new(appSecret, to_enc, digestmod=hashlib.sha256).digest()).decode()
return signature
# 获取接口数据
def get_list(url):
nonce = get_nonce()
signature = get_signature(nonce)
print(nonce)
print(signature)
payload = {}
headers = {
'authority': 'bizapi.csdn.net',
'pragma': 'no-cache',
'cache-control': 'no-cache',
'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
'dnt': '1',
'x-ca-signature-headers': 'x-ca-key,x-ca-nonce',
'x-ca-signature': signature,
'x-ca-nonce': nonce,
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',
'uber-trace-id': '50d7304716310079669041001c6a0ab7:50d7304716310089:0:0',
'accept': 'application/json, text/plain, */*',
'x-ca-key': '203871397',
'origin': 'https://ask.csdn.net',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://ask.csdn.net/?spm=1005.2025.3001.4492&rewardType=2&stateType=5&sortBy=1&quick=3',
'accept-language': 'zh-CN,zh;q=0.9',
}
response = requests.request("GET", url, headers=headers, data=payload).json()
for item in response['data']['list']:
print(item['title'])
if __name__ == '__main__':
get_list(f"https://bizapi.csdn.net/mp/ask/v1/questions/list?pageNo=1&pageSize=30&communityInfo=1&rewardType=2&type=5&sortBy=1&quick=3")
\ No newline at end of file
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册