首页 文章 精选 留言 我的

精选列表

搜索[博客系统],共10000篇文章
优秀的个人博客,低调大师

[雪峰磁针石博客]flask构建自动化测试平台3-模板

3-模板 理想情况下,前端和后端组件之间的完全隔离。我们可以在很大程度上使用Jinja来实现这一目标。 到本章将扩展我们的应用程序,为所选出版物显示不止一个标题。我们将为每个出版物显示多篇文章,每篇文章都链接到原始文章,我们的逻辑和视图组件将在很大程度上分开。在本章中,我们将介绍以下主题: 介绍Jinja Jinja模板使用 本文最新版本 介绍Jinja Jinja是一个Python模板引擎。它允许我们轻松定义由Python填充的动态HTML块。即使对于多个静态网页的网站,HTML模板也很有用有,如修改页眉和页脚。Flask基于Jinja,尽管可以单独使用Jinja,但Jinja仍然是Flask的固有部分。Flask和Flask提供了几种直接与Jinja工作的方法。默认情况下,Flask假定你存储了所有的Jinja模板位于您的应用程序的templates子目录中。 Jinja模板使用 home.html <html> <head> <title>Headlines</title> </head> <body> <h1>Headlines</h1> {% for article in articles %} <b><a href="{{article.link}}">{{article.title}}</a></b><br /> <i>{{article.published}}</i><br /> <p>{{article.summary}}</p> <hr /> {% endfor %} </body> </html> import feedparser from flask import Flask from flask import render_template app = Flask(__name__) RSS_FEEDS = {'bbc': 'http://feeds.bbci.co.uk/news/rss.xml', 'cnn': 'http://rss.cnn.com/rss/edition.rss', 'fox': 'http://feeds.foxnews.com/foxnews/latest', 'iol': 'http://www.iol.co.za/cmlink/1.640'} @app.route("/") @app.route("/<publication>") def get_news(publication="bbc"): feed = feedparser.parse(RSS_FEEDS[publication]) return render_template("home.html", articles=feed['entries']) if __name__ == "__main__": app.run(host='0.0.0.0',port=8000, debug=True) 参考资料 本文相关书籍下载 讨论 钉钉免费群21745728 qq群144081101 567351477 本文涉及的python测试开发库 谢谢点赞! 本文代码地址

优秀的个人博客,低调大师

[雪峰磁针石博客]flask构建自动化测试平台1-hello

简介 第一部分 Flask实例。学习使用Flask开发,构建功能完备的Web应用程序。我们开发了动态的头条新闻应用程序,可显示最新的新闻标题以及最新的货币和天气信息。在项目二中,我们构建了由MySQL数据库支持的犯罪地图应用程序,允许用户提交犯罪信息和犯罪地点,以便绘制区域内的危险区域和其他犯罪趋势。在最后的项目中,我们将Flask与更多现代技术结合在一起,例如Twitter的Bootstrap和NoSQL数据库MongoDB,以创建Waiter Caller应用程序,允许餐厅顾客轻松地将服务员叫到他们的桌子。 第二部分 Flask框架菜谱。涉及Flask的不同配置方式,如何使用模板并学习ORM和视图层。您将看到如何编写管理界面,随后进行错误调试和记录。最后,你会了解平台上的不同部署。 第三部分 掌握Flask,从简单的Flask应用程序展示

优秀的个人博客,低调大师

[雪峰磁针石博客]python库介绍-collections:高性能容器数据类型

简介 2.4新增 源代码:Lib/collections.py and Lib/_abcoll.py 提供了替换dict, list, set和tuple的数据类型。 主要类型如下: namedtuple(): 命名元组,创建有名字域的元组子类的工厂函数。python 2.6新增。 deque:双端队列,类似于列表,两端进栈和出栈都比较快速。python 2.4新增。 Counter:字典的子类,用于统计哈希对象。python 2.7新增。 OrderedDict:有序字典,字典的子类,记录了添加顺序。python 2.7新增。 defaultdict:dict的子类,调用一个工厂函数支持不存在的值。python 2.5新增。 还提供了抽象基类,用来测试类是否提供了特殊接口,不管是哈希或者映射。 Counter 计数器(Counter)是一个容器,用来跟踪值出现了多少次。和其他语言中的bag或multiset类似。 计数器支持三种形式的初始化。构造函数可以调用序列,包含key和计数的字典,或使用关键字参数。 import collections print(collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])) print(collections.Counter({'a': 2, 'b': 3, 'c': 1})) print(collections.Counter(a=2, b=3, c=1)) 执行结果: $ python3 collections_counter_init.py Counter({'b': 3, 'a': 2, 'c': 1}) Counter({'b': 3, 'a': 2, 'c': 1}) Counter({'b': 3, 'a': 2, 'c': 1}) 注意key的出现顺序是根据计数的从大到小。 可以创建空的计数器,再update: import collections c = collections.Counter() print('Initial :{0}'.format(c)) c.update('abcdaab') print('Sequence:{0}'.format(c)) c.update({'a': 1, 'd': 5}) print('Dict :{0}'.format(c)) 执行结果: python3.5 collections_counter_update.py* Initial :Counter() Sequence:Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1}) Dict :Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1}) 访问计数 import collections c = collections.Counter('abcdaab') for letter in 'abcde': print('{0} : {1}'.format(letter, c[letter])) 执行结果: $ python3.5 collections_counter_get_values.py a : 3 b : 2 c : 1 d : 1 e : 0 注意这里不存在的元素也会统计为0。 elements方法可以列出所有元素: import collections c = collections.Counter('extremely') c['z'] = 0 print(c) print(list(c.elements())) 执行结果: $ python3.5 collections_counter_elements.py Counter({'e': 3, 'y': 1, 'r': 1, 'x': 1, 'm': 1, 'l': 1, 't': 1, 'z': 0}) ['y', 'r', 'x', 'm', 'l', 't', 'e', 'e', 'e'] 注意后面并没有输出计数为0的元素。 most_common()可以提取出最常用的元素。 import collections c = collections.Counter() with open('/etc/adduser.conf', 'rt') as f: for line in f: c.update(line.rstrip().lower()) print('Most common:') for letter, count in c.most_common(3): print('{0}: {1}'.format(letter, count)) 执行结果: $ python3.5 collections_counter_most_common.py Most common: : 401 e: 310 s: 221 Counter还支持算术和集合运算,它们都只会保留数值为正整数的key。 import collections import pprint c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']) c2 = collections.Counter('alphabet') print('C1:') pprint.pprint(c1) print('C2:') pprint.pprint(c2) print('\nCombined counts:') print(c1 + c2) print('\nSubtraction:') print(c1 - c2) print('\nIntersection (taking positive minimums):') print(c1 & c2) print('\nUnion (taking maximums):') print(c1 | c2) 执行结果: $ python3 collections_counter_arithmetic.py C1: Counter({'b': 3, 'a': 2, 'c': 1}) C2: Counter({'a': 2, 't': 1, 'l': 1, 'e': 1, 'b': 1, 'p': 1, 'h': 1}) Combined counts: Counter({'b': 4, 'a': 4, 'p': 1, 'e': 1, 'c': 1, 't': 1, 'l': 1, 'h': 1}) Subtraction: Counter({'b': 2, 'c': 1}) Intersection (taking positive minimums): Counter({'a': 2, 'b': 1}) Union (taking maximums): Counter({'b': 3, 'a': 2, 'p': 1, 'e': 1, 'c': 1, 't': 1, 'l': 1, 'h': 1}) 上面的例子让人觉得collections只能处理单个字符。其实不是这样的,请看标准库中的实例。 from collections import Counter import pprint import re cnt = Counter() for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: cnt[word] += 1 pprint.pprint(cnt) cnt = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue']) pprint.pprint(cnt) words = re.findall('\w+', open('/etc/adduser.conf').read().lower()) print(Counter(words).most_common(10)) 执行结果: $ python3 collections_counter_normal.py Counter({'blue': 3, 'red': 2, 'green': 1}) Counter({'blue': 3, 'red': 2, 'green': 1}) [('the', 27), ('is', 13), ('be', 12), ('if', 12), ('will', 12), ('user', 10), ('home', 9), ('default', 9), ('to', 9), ('users', 8)] 第1段代码和第2段的代码效果式样的,后面一段代码通过Counter实现了简单的单词的统计功能。比如面试题:使用python打印出/etc/ssh/sshd_config出现次数最高的10个单词及其出现次数。 下面看看Counter的相关定义: class collections.Counter([iterable-or-mapping]) 。注意Counter是无序的字典。在key不存在的时候返回0. c['sausage'] = 0。设置值为0不会删除元素,要使用del c['sausage']。 除了标准的字典方法,额外增加了: elements() :返回一个包含所有元素的迭代器,忽略小于1的计数。 most_common([n]):返回最常用的元素及其计数的列表。默认返回所有元素。 subtract([iterable-or-mapping]) :相减。 namedtuple 命名元组和普通元组的的内存效率差不多。它不会针对每个实例生成字典。 import collections Person = collections.namedtuple('Person', 'name age gender') print('Type of Person:{0}'.format(type(Person))) bob = Person(name='Bob', age=30, gender='male') print('\nRepresentation: {0}'.format(bob)) jane = Person(name='Jane', age=29, gender='female') print('\nField by name: {0}'.format(jane.name)) print('\nFields by index:') for p in [bob, jane]: print('{0} is a {1} year old {2}'.format(*p)) 执行结果: $ python3 collections_namedtuple_person.py Type of Person:<class 'type'> Representation: Person(name='Bob', age=30, gender='male') Field by name: Jane Fields by index: Bob is a 30 year old male Jane is a 29 year old female 从上例可以看出命名元组Person类和excel的表头类似,给下面的每个列取个名字,真正excel行数据则存储在Person类的实例中。好处在于可以jane.name这样的形式访问,比记元组的index要直观。 注意列名在实现内部其实是个标识符,所以不能和关键字冲突,只能用字母或者下划线开头。下例会报错: import collections try: collections.namedtuple('Person', 'name class age gender') except ValueError as err: print(err) try: collections.namedtuple('Person', 'name age gender age') except ValueError as err: print(err) 执行结果: $ python3 collections_namedtuple_bad_fields.py Type names and field names cannot be a keyword: 'class' Encountered duplicate field name: 'age' 设置rename=True,列名会在冲突时自动重命名,不过这种重命名并不美观。 import collections with_class = collections.namedtuple('Person', 'name class age gender', rename=True) print(with_class._fields) two_ages = collections.namedtuple('Person', 'name age gender age', rename=True) print(two_ages._fields) 执行结果: $ python collections_namedtuple_rename.py ('name', '_1', 'age', 'gender') ('name', 'age', 'gender', '_3') 定义 collections.namedtuple(typename, field_names, verbose=False) 返回一个命名元组类。如果verbose为True,会打印类定义信息 命名元组在处理数据库的时候比较有用: ChainMap 映射链 用于查找多个字典。 ChainMap管理一系列字典,按顺序根据key查找值。 访问值: API和字典类似。 collections_chainmap_read.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m = collections.ChainMap(a, b) print('Individual Values') print('a = {}'.format(m['a'])) print('b = {}'.format(m['b'])) print('c = {}'.format(m['c'])) print() print('m = {}'.format(m)) print('Keys = {}'.format(list(m.keys()))) print('Values = {}'.format(list(m.values()))) print() print('Items:') for k, v in m.items(): print('{} = {}'.format(k, v)) print() print('"d" in m: {}'.format(('d' in m))) 执行结果: $ python3 collections_chainmap_read.py Individual Values a = A b = B c = C m = ChainMap({'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'}) Keys = ['c', 'a', 'b'] Values = ['C', 'A', 'B'] Items: c = C a = A b = B "d" in m: False 调整顺序 collections_chainmap_reorder.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m = collections.ChainMap(a, b) print(m.maps) print('c = {}\n'.format(m['c'])) # reverse the list m.maps = list(reversed(m.maps)) print(m.maps) print('c = {}'.format(m['c'])) 执行结果: $ python3 collections_chainmap_reorder.py [{'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'}] c = C [{'c': 'D', 'b': 'B'}, {'c': 'C', 'a': 'A'}] c = D 更新值 更新原字典: collections_chainmap_update_behind.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m = collections.ChainMap(a, b) print('Before: {}'.format(m['c'])) a['c'] = 'E' print('After : {}'.format(m['c'])) 执行结果 $ python3 collections_chainmap_update_behind.py Before: C After : E 直接更新ChainMap: collections_chainmap_update_directly.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m = collections.ChainMap(a, b) print('Before:', m) m['c'] = 'E' print('After :', m) print('a:', a) 执行结果 $ python3 collections_chainmap_update_directly.py Before: ChainMap({'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'}) After : ChainMap({'c': 'E', 'a': 'A'}, {'c': 'D', 'b': 'B'}) a: {'c': 'E', 'a': 'A'} ChainMap可以方便地在前面插入字典,这样可以避免修改原来的字典。 collections_chainmap_new_child.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m1 = collections.ChainMap(a, b) m2 = m1.new_child() print('m1 before:', m1) print('m2 before:', m2) m2['c'] = 'E' print('m1 after:', m1) print('m2 after:', m2) 执行结果 $ python3 collections_chainmap_new_child.py m1 before: ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}) m2 before: ChainMap({}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}) m1 after: ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}) m2 after: ChainMap({'c': 'E'}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}) 还可以通过传入字典的方式 collections_chainmap_new_child_explicit.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} c = {'c': 'E'} m1 = collections.ChainMap(a, b) m2 = m1.new_child(c) print('m1["c"] = {}'.format(m1['c'])) print('m2["c"] = {}'.format(m2['c'])) 执行结果 $ python3 collections_chainmap_new_child_explicit.py m1["c"] = C m2["c"] = E 另外一种等价的方式: m2 = collections.ChainMap(c, *m1.maps) 参考资料 本文最新版本地址 讨论 钉钉免费群21745728 qq群144081101 567351477 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 python官方文档:https://docs.python.org/3/library/collections.html https://pymotw.com/3/collections/chainmap.html http://collections-extended.lenzm.net/ https://pypi.python.org/pypi/collections-extended/ 本文代码地址

优秀的个人博客,低调大师

【博客大赛】基于百度飞桨paddlepaddle的疫情可视化实战

百度paddlepaddle安装及疫情可视化实战 1. paddle安装可以参考官方文档 地址链接: https://www.paddlepaddle.org.cn/install/quick选择合适自己的方式进行安装 2. 疫情数据可视化 思路:通过爬虫得到数据并且通过pyecharts进行可视化 爬取丁香园公开的统计数据 上网的全过程: 普通用户打开浏览器 --> 往目标站点发送请求 --> 接收响应数据 --> 渲染到页面上。 爬虫程序模拟浏览器 --> 往目标站点发送请求 --> 接收响应数据 --> 提取有用的数据 --> 保存到本地/数据库。 爬虫的过程: 1.发送请求(requests模块) 2.获取响应数据(服务器返回) 3.解析并提取数据(re正则) 4.保存数据 我们用到了:request模块: requests是python实现的简单易用的HTTP库,官网地址:http://cn.python-requests.org/zh_CN/latest/ re模块: re模块是python用于匹配字符串的模块,该模块中提供的很多功能是基于正则表达式实现的, import json import re import requests import datetime today = datetime.date.today().strftime('%Y%m%d') #20200315 def crawl_dxy_data(): """ 爬取丁香园实时统计数据,保存到data目录下,以当前日期作为文件名,存JSON文件 """ response = requests.get('https://ncov.dxy.cn/ncovh5/view/pneumonia') #request.get()用于请求目标网站 print(response.status_code) # 打印状态码 try: url_text = response.content.decode() #更推荐使用response.content.deocde()的方式获取响应的html页面 #print(url_text) url_content = re.search(r'window.getAreaStat = (.*?)}]}catch', #re.search():扫描字符串以查找正则表达式模式产生匹配项的第一个位置 ,然后返回相应的match对象。 url_text, re.S) #在字符串a中,包含换行符\n,在这种情况下:如果不使用re.S参数,则只在每一行内进行匹配,如果一行没有,就换下一行重新开始; #而使用re.S参数以后,正则表达式会将这个字符串作为一个整体,在整体中进行匹配。 texts = url_content.group() #获取匹配正则表达式的整体结果 content = texts.replace('window.getAreaStat = ', '').replace('}catch', '') #去除多余的字符 json_data = json.loads(content) with open('data/' + today + '.json', 'w', encoding='UTF-8') as f: json.dump(json_data, f, ensure_ascii=False) except: print('<Response [%s]>' % response.status_code) def crawl_statistics_data(): """ 获取各个省份历史统计数据,保存到data目录下,存JSON文件 """ with open('data/'+ today + '.json', 'r', encoding='UTF-8') as file: json_array = json.loads(file.read()) statistics_data = {} for province in json_array: response = requests.get(province['statisticsData']) try: statistics_data[province['provinceShortName']] = json.loads(response.content.decode())['data'] except: print('<Response [%s]> for url: [%s]' % (response.status_code, province['statisticsData'])) with open("data/statistics_data.json", "w", encoding='UTF-8') as f: json.dump(statistics_data, f, ensure_ascii=False) if __name__ == '__main__': crawl_dxy_data() crawl_statistics_data() 运行以上代码,我们需要在代码同目录下创建data文件夹运行成功后,在data文件夹下能够得到两个文件分别是:statistics_data.json和一个今天日期的json 安装第三方库pyecharts Echarts 是一个由百度开源的数据可视化工具,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可。而 Python 是一门富有表达力的语言,很适合用于数据处理。当数据分析遇上数据可视化时,pyecharts 诞生了。pyecharts api可以参考:https://pyecharts.org/#/zh-cn/chart_api 使用 options 配置项,在 pyecharts 中,一切皆 Options。 主要分为全局配置组件和系列配置组件。 (1)系列配置项 set_series_opts(),可配置图元样式、文字样式、标签样式、点线样式等; (2)全局配置项 set_global_opts(),可配置标题、动画、坐标轴、图例等; pyecharts非常好用!!!我们通过pip安装 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyecharts 如果下载时出现断线和速度过慢的问题导致下载失败,可以尝试使用其他国内源当出现Successfully installed pyecharts-1.7.1 simplejson-3.17.0时我们就安装成功了 数据可视化地图 全国地图 import json import datetime from pyecharts.charts import Map from pyecharts import options as opts # 读原始数据文件 today = datetime.date.today().strftime('%Y%m%d') #20200315 datafile = 'data/'+ today + '.json' with open(datafile, 'r', encoding='UTF-8') as file: json_array = json.loads(file.read()) # 分析全国实时确诊数据:'confirmedCount'字段 china_data = [] for province in json_array: china_data.append((province['provinceShortName'], province['confirmedCount'])) china_data = sorted(china_data, key=lambda x: x[1], reverse=True) #reverse=True,表示降序,反之升序 print(china_data) # 全国疫情地图 # 自定义的每一段的范围,以及每一段的特别的样式。 pieces = [ {'min': 10000, 'color': '#540d0d'}, {'max': 9999, 'min': 1000, 'color': '#9c1414'}, {'max': 999, 'min': 500, 'color': '#d92727'}, {'max': 499, 'min': 100, 'color': '#ed3232'}, {'max': 99, 'min': 10, 'color': '#f27777'}, {'max': 9, 'min': 1, 'color': '#f7adad'}, {'max': 0, 'color': '#f7e4e4'}, ] labels = [data[0] for data in china_data] counts = [data[1] for data in china_data] m = Map() m.add("累计确诊", [list(z) for z in zip(labels, counts)], 'china') #系列配置项,可配置图元样式、文字样式、标签样式、点线样式等 m.set_series_opts(label_opts=opts.LabelOpts(font_size=12), is_show=False) #全局配置项,可配置标题、动画、坐标轴、图例等 m.set_global_opts(title_opts=opts.TitleOpts(title='全国实时确诊数据', subtitle='数据来源:丁香园'), legend_opts=opts.LegendOpts(is_show=False), visualmap_opts=opts.VisualMapOpts(pieces=pieces, is_piecewise=True, #是否为分段型 is_show=True)) #是否显示视觉映射配置 #render()会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件,也可以传入路径参数,如 m.render("mycharts.html") m.render(path='./data/数据.html') 这里代码都有完善的注释,就不拆解来讲了 ### 数据可视化湖北省地图 ```python import json import datetime from pyecharts.charts import Map from pyecharts import options as opts # 读原始数据文件 today = datetime.date.today().strftime('%Y%m%d') #20200315 datafile = 'data/'+ today + '.json' with open(datafile, 'r', encoding='UTF-8') as file: json_array = json.loads(file.read()) # 分析湖北省实时确诊数据 # 读入规范化的城市名称,用于规范化丁香园数据中的城市简称 with open('/home/aistudio/data/data24815/pycharts_city.txt', 'r', encoding='UTF-8') as f: defined_cities = [line.strip() for line in f.readlines()] def format_city_name(name, defined_cities): for defined_city in defined_cities: if len((set(defined_city) & set(name))) == len(name): name = defined_city if name.endswith('市') or name.endswith('区') or name.endswith('县') or name.endswith('自治州'): return name return name + '市' return None province_name = '湖北' for province in json_array: if province['provinceName'] == province_name or province['provinceShortName'] == province_name: json_array_province = province['cities'] hubei_data = [(format_city_name(city['cityName'], defined_cities), city['confirmedCount']) for city in json_array_province] hubei_data = sorted(hubei_data, key=lambda x: x[1], reverse=True) print(hubei_data) labels = [data[0] for data in hubei_data] counts = [data[1] for data in hubei_data] pieces = [ {'min': 10000, 'color': '#540d0d'}, {'max': 9999, 'min': 1000, 'color': '#9c1414'}, {'max': 999, 'min': 500, 'color': '#d92727'}, {'max': 499, 'min': 100, 'color': '#ed3232'}, {'max': 99, 'min': 10, 'color': '#f27777'}, {'max': 9, 'min': 1, 'color': '#f7adad'}, {'max': 0, 'color': '#f7e4e4'}, ] m = Map() m.add("累计确诊", [list(z) for z in zip(labels, counts)], '湖北') m.set_series_opts(label_opts=opts.LabelOpts(font_size=12), is_show=False) m.set_global_opts(title_opts=opts.TitleOpts(title='湖北省实时确诊数据', subtitle='数据来源:丁香园'), legend_opts=opts.LegendOpts(is_show=False), visualmap_opts=opts.VisualMapOpts(pieces=pieces, is_piecewise=True, is_show=True)) m.render(path='./data/湖北省数据.html') 增长趋势 on from pyecharts.charts import Line from pyecharts import options as opts # 读原始数据文件 datafile = 'data/statistics_data.json' with open(datafile, 'r', encoding='UTF-8') as file: json_dict = json.loads(file.read()) # 分析各省份2月1日至今的新增确诊数据:'confirmedIncr' statistics__data = {} for province in json_dict: statistics__data[province] = [] for da in json_dict[province]: if da['dateId'] >= 20200201: statistics__data[province].append(da['confirmedIncr']) # 获取日期列表 dateId = [str(da['dateId'])[4:6] + '-' + str(da['dateId'])[6:8] for da in json_dict['湖北'] if da['dateId'] >= 20200201] # 全国新增趋势 all_statis = np.array([0] * len(dateId)) for province in statistics__data: all_statis = all_statis + np.array(statistics__data[province]) all_statis = all_statis.tolist() # 湖北新增趋势 hubei_statis = statistics__data['湖北'] # 湖北以外的新增趋势 other_statis = [all_statis[i] - hubei_statis[i] for i in range(len(dateId))] line = Line() line.add_xaxis(dateId) line.add_yaxis("全国新增确诊病例", #图例 all_statis, #数据 is_smooth=True, #是否平滑曲线 linestyle_opts=opts.LineStyleOpts(width=4, color='#B44038'),#线样式配置项 itemstyle_opts=opts.ItemStyleOpts(color='#B44038', #图元样式配置项 border_color="#B44038", #颜色 border_width=10)) #图元的大小 line.add_yaxis("湖北新增确诊病例", hubei_statis, is_smooth=True, linestyle_opts=opts.LineStyleOpts(width=2, color='#4E87ED'), label_opts=opts.LabelOpts(position='bottom'), #标签在折线的底部 itemstyle_opts=opts.ItemStyleOpts(color='#4E87ED', border_color="#4E87ED", border_width=3)) line.add_yaxis("其他省份新增病例", other_statis, is_smooth=True, linestyle_opts=opts.LineStyleOpts(width=2, color='#F1A846'), label_opts=opts.LabelOpts(position='bottom'), #标签在折线的底部 itemstyle_opts=opts.ItemStyleOpts(color='#F1A846', border_color="#F1A846", border_width=3)) line.set_global_opts(title_opts=opts.TitleOpts(title="新增确诊病例", subtitle='数据来源:丁香园'), yaxis_opts=opts.AxisOpts(max_=16000, min_=1, type_="log", #坐标轴配置项 splitline_opts=opts.SplitLineOpts(is_show=True),#分割线配置项 axisline_opts=opts.AxisLineOpts(is_show=True)))#坐标轴刻度线配置项 line.render(path='./data/趋势图.html') 需要自己完成的饼状图 import json import datetime from pyecharts.charts import Map, Pie from pyecharts import options as opts # 读原始数据文件 today = datetime.date.today().strftime('%Y%m%d') #20200315 datafile = 'data/'+ today + '.json' with open(datafile, 'r', encoding='UTF-8') as file: json_array = json.loads(file.read()) # 分析全国实时确诊数据:'confirmedCount'字段 china_data = [] for province in json_array: china_data.append((province['provinceShortName'], province['confirmedCount'])) china_data = sorted(china_data, key=lambda x: x[1], reverse=True) #reverse=True,表示降序,反之升序 print(china_data) labels = [data[0] for data in china_data] counts = [data[1] for data in china_data] m = Pie(init_opts=opts.InitOpts(height='900px')) m.add("累计确诊", [list(z) for z in zip(labels, counts)], center=["50%", "60%"], radius=['0%', '40%']) #,)center=[100,50] m.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}", font_size=12), is_show=False) #全局配置项,可配置标题、动画、坐标轴、图例等 m.set_global_opts(title_opts=opts.TitleOpts(title='全国实时确诊数据', subtitle='数据来源:丁香园'), legend_opts=opts.LegendOpts(is_show=False, type_="scroll", pos_left="80%", orient="vertical"), ) #render()会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件,也可以传入路径参数,如 m.render("mycharts.html") m.render(path='./data/饼状图.html') over!!!

优秀的个人博客,低调大师

[雪峰磁针石博客]大数据Hadoop工具python教程2-python访问HDFS

https://pypi.org/project/hdfs3 已经不维护PyArrowhttps://pypi.org/project/hdfs/https://pypi.org/project/snakebite/ python2中比较好,对python3支持不好。 hdfs和PyArrow比较常用,这里以hdfs为例: 快速入门 from hdfs import InsecureClient client = InsecureClient('http://localhost:50070', user='hduser_') fs_folders_list = client.list("/") print(fs_folders_list) with client.read('/user/hduser/input.txt', enco

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册