首页 文章 精选 留言 我的

精选列表

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

Hadoop 1.0.3 在CentOS 6.2上安装过程 [个人安装通过的全程记录]

//安装SSH [root@localhost /]# sudo yum install ssh //生成密钥 [root@localhost /]# ssh-keygen (可以一路回车) 生成下面两个文件: /root/.ssh/id_rsa /root/.ssh/id_rsa.pub [root@localhost .ssh]# cd /root/.ssh/ //实际情况是把公钥复制到另外一台机器上,并且写入到另外一台机器上的authorized_keys文件中 [root@localhost .ssh]# cat ./id_rsa.pub>>./authorized_keys [root@localhost .ssh]# cd /home (另外一个更简单的复制方法是使用 ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.1.201) //配置JDK环境变量 [root@localhost opt]# vi /etc/profile export JAVA_HOME=/opt/jdk1.6.0_31 export PATH=$JAVA_HOME/bin:$PATH:. //使配置生效 [root@localhost opt]# source /etc/profile //安装Hadoop 1.0.3 [root@localhost opt]# rpm -i hadoop-1.0.3-1.x86_64.rpm //查看安装后的Hadoop版本号信息 [root@localhost opt]# hadoop version (如果报错,请检查hadoop-env.sh中的java路径配置是否正确) 修改hadoop配置文件(/etc/hadoop) [root@localhost hadoop]# cd /etc/hadoop [root@localhost hadoop]# vi hadoop-env.sh export JAVA_HOME=/opt/jdk1.6.0_31 [root@localhost hadoop]# vi core-site.xml <configuration> <property> <name>fs.default.name</name> <value>hdfs://192.168.1.101:9000</value> </property> <property> <name>hadoop.tmp.dir</name> <value>/hadoop</value> </property> </configuration> [root@localhost hadoop]# vi hdfs-site.xml <configuration> <property> <name>dfs.replication</name> <value>1</value> </property> </configuration> [root@localhost hadoop]# vi mapred-site.xml <configuration> <property> <name>mapred.job.tracker</name> <value>192.168.1.101:9001</value> </property> </configuration> //格式化文件系统 [root@localhost opt]# hadoop namenode -format //启动Hadoop相关的所有服务 (/usr/sbin) [root@localhost sbin]# start-all.sh 或 [root@localhost opt]# /usr/sbin/start-all.sh (如果没有执行权限,需要将/usr/sbin目录下的相关sh文件设置执行权限) 说明: start-all.sh stop-all.sh start-dfs.sh stop-dfs.sh start-mapred.sh stop-mapred.sh slaves.sh //jps查看已经启动的服务进程信息 [root@localhost hadoop]# jps 5131 NameNode 5242 DataNode 5361 SecondaryNameNode 5583 TaskTracker 5463 JobTracker 6714 Jps 防火墙需要开放的端口: 9000 9001 50010 (访问 http://192.168.1.101:50070 http://192.168.1.101:50030) [root@localhost hadoop]# hadoop dfsadmin -report 为运行例子 wordcount 作准备 [root@localhost opt]# hadoop fs -mkdir input [root@localhost opt]# echo "Hello World Bye World" > file01 [root@localhost opt]# echo "Hello Hadoop Goodbye Hadoop" > file02 [root@localhost opt]# hadoop fs -copyFromLocal ./file0* input 运行例子 wordcount [root@localhost opt]# hadoop jar /usr/share/hadoop/hadoop-examples-1.0.3.jar wordcount input output 12/08/11 12:00:30 INFO input.FileInputFormat: Total input paths to process : 2 12/08/11 12:00:30 INFO util.NativeCodeLoader: Loaded the native-hadoop library 12/08/11 12:00:30 WARN snappy.LoadSnappy: Snappy native library not loaded 12/08/11 12:00:31 INFO mapred.JobClient: Running job: job_201208111137_0001 12/08/11 12:00:32 INFO mapred.JobClient: map 0% reduce 0% 12/08/11 12:01:05 INFO mapred.JobClient: map 100% reduce 0% 12/08/11 12:01:20 INFO mapred.JobClient: map 100% reduce 100% 12/08/11 12:01:25 INFO mapred.JobClient: Job complete: job_201208111137_0001 12/08/11 12:01:25 INFO mapred.JobClient: Counters: 29 12/08/11 12:01:25 INFO mapred.JobClient: Job Counters 12/08/11 12:01:25 INFO mapred.JobClient: Launched reduce tasks=1 12/08/11 12:01:25 INFO mapred.JobClient: SLOTS_MILLIS_MAPS=49499 12/08/11 12:01:25 INFO mapred.JobClient: Total time spent by all reduces waiting after reserving slots (ms)=0 12/08/11 12:01:25 INFO mapred.JobClient: Total time spent by all maps waiting after reserving slots (ms)=0 12/08/11 12:01:25 INFO mapred.JobClient: Launched map tasks=2 12/08/11 12:01:25 INFO mapred.JobClient: Data-local map tasks=2 12/08/11 12:01:25 INFO mapred.JobClient: SLOTS_MILLIS_REDUCES=12839 12/08/11 12:01:25 INFO mapred.JobClient: File Output Format Counters 12/08/11 12:01:25 INFO mapred.JobClient: Bytes Written=41 12/08/11 12:01:25 INFO mapred.JobClient: FileSystemCounters 12/08/11 12:01:25 INFO mapred.JobClient: FILE_BYTES_READ=79 12/08/11 12:01:25 INFO mapred.JobClient: HDFS_BYTES_READ=276 12/08/11 12:01:25 INFO mapred.JobClient: FILE_BYTES_WRITTEN=64705 12/08/11 12:01:25 INFO mapred.JobClient: HDFS_BYTES_WRITTEN=41 12/08/11 12:01:25 INFO mapred.JobClient: File Input Format Counters 12/08/11 12:01:25 INFO mapred.JobClient: Bytes Read=50 12/08/11 12:01:25 INFO mapred.JobClient: Map-Reduce Framework 12/08/11 12:01:25 INFO mapred.JobClient: Map output materialized bytes=85 12/08/11 12:01:25 INFO mapred.JobClient: Map input records=2 12/08/11 12:01:25 INFO mapred.JobClient: Reduce shuffle bytes=85 12/08/11 12:01:25 INFO mapred.JobClient: Spilled Records=12 12/08/11 12:01:25 INFO mapred.JobClient: Map output bytes=82 12/08/11 12:01:25 INFO mapred.JobClient: CPU time spent (ms)=4770 12/08/11 12:01:25 INFO mapred.JobClient: Total committed heap usage (bytes)=246751232 12/08/11 12:01:25 INFO mapred.JobClient: Combine input records=8 12/08/11 12:01:25 INFO mapred.JobClient: SPLIT_RAW_BYTES=226 12/08/11 12:01:25 INFO mapred.JobClient: Reduce input records=6 12/08/11 12:01:25 INFO mapred.JobClient: Reduce input groups=5 12/08/11 12:01:25 INFO mapred.JobClient: Combine output records=6 12/08/11 12:01:25 INFO mapred.JobClient: Physical memory (bytes) snapshot=391634944 12/08/11 12:01:25 INFO mapred.JobClient: Reduce output records=5 12/08/11 12:01:25 INFO mapred.JobClient: Virtual memory (bytes) snapshot=3159781376 12/08/11 12:01:25 INFO mapred.JobClient: Map output records=8 //查看统计结果 [root@localhost opt]# hadoop fs -cat output/part-r-00000 Bye1 Goodbye1 Hadoop2 Hello2 World2 //--------------------------------------- 作业日志存放目录: /var/log/hadoop/root/userlogs/ //--------------------------------------- 安装 hadoop-1.0.3-1 后,存放的目录有: /etc/hadoop /var/run/hadoop /var/log/hadoop /usr/share/hadoop /usr/share/doc/hadoop /usr/etc/hadoop /usr/bin/hadoop(文件) /usr/include/hadoop

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

基于百度飞桨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!!!

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

[python作业AI毕业设计博客]英文原版新书下载:Impractical Python Projects - 2019.Pdf

python测试开发项目实战-目录 python工具书籍下载-持续更新 python 3.7极速入门教程 - 目录 下载:Impractical Python Projects - 2019.Pdf Impractical Python Projects is a collection of fun and educational projects designed to entertain programmers while enhancing their Python skills. It picks up where the complete beginner books leave off, expanding on existing concepts and introducing new tools that you'll use every day. And to keep things interesting, each project includes a zany twist featuring historical incidents, pop culture references, and literary allusions. You'll flex your problem-solving skills and employ Python's many useful libraries to do things like:• Help James Bond crack a high-tech safe with a hill-climbing algorithm • Write haiku poems using Markov Chain Analysis• Use genetic algorithms to breed a race of gigantic rats• Crack the world's most successful military cipher using cryptanalysis• Derive the anagram, "I am Lord Voldemort" using linguistical sieves • Plan your parents' secure retirement with Monte Carlo simulation• Save the sorceress Zatanna from a stabby death using palingrams• Model the Milky Way and calculate our odds of detecting alien civilizations• Help the world's smartest woman win the Monty Hall problem argument• Reveal Jupiter's Great Red Spot using optical stacking• Save the head of Mary, Queen of Scots with steganography• Foil corporate security with invisible electronic ink Simulate volcanoes, map Mars, and more, all while gaining valuable experience using free modules like Tkinter, matplotlib, Cprofile, Pylint, Pygame, Pillow, and Python-Docx. Whether you're looking to pick up some new Python skills or just need a pick-me-up, you'll find endless educational, geeky fun with Impractical Python Projects. e-Books Highlight Edition1st Edition ISBN159327890X Posted on12/3/2018 FormatPdf Page Count426 Pages AuthorLee Vaughan, 参考资料 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 2018最佳人工智能机器学习工具书及下载(持续更新)

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

[雪峰磁针石博客]计算机视觉opcencv工具深度学习快速实战2 opencv快速入门

opencv基本操作 # -*- coding: utf-8 -*- # Author: xurongzhong#126.com wechat:pythontesting qq:37391319 # 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入) # qq群:144081101 591302926 567351477 # CreateDate: 2018-11-17 import imutils import cv2 # 读取图片信息 image = cv2.imread("jp.png") (h, w, d) = image.shape print("width={}, height={}, depth={}".format(w, h, d)) # 显示图片 cv2.imshow("Image", image) cv2.waitKey(0) # 访问像素 (B, G, R) = image[100, 50] print("R={}, G={}, B={}".format(R, G, B)) # 选取图片区间 ROI (Region of Interest) roi = image[60:160, 320:420] cv2.imshow("ROI", roi) cv2.waitKey(0) # 缩放 resized = cv2.resize(image, (200, 200)) cv2.imshow("Fixed Resizing", resized) cv2.waitKey(0) # 按比例缩放 r = 300.0 / w dim = (300, int(h * r)) resized = cv2.resize(image, dim) cv2.imshow("Aspect Ratio Resize", resized) cv2.waitKey(0) # 使用imutils缩放 resized = imutils.resize(image, width=300) cv2.imshow("Imutils Resize", resized) cv2.waitKey(0) # 顺时针旋转45度 center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, -45, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("OpenCV Rotation", rotated) cv2.waitKey(0) # 使用imutils旋转 rotated = imutils.rotate(image, -45) cv2.imshow("Imutils Rotation", rotated) cv2.waitKey(0) # 使用imutils无损旋转 rotated = imutils.rotate_bound(image, 45) cv2.imshow("Imutils Bound Rotation", rotated) cv2.waitKey(0) # apply a Gaussian blur with a 11x11 kernel to the image to smooth it, # useful when reducing high frequency noise 高斯模糊 # https://www.pyimagesearch.com/2016/07/25/convolutions-with-opencv-and-python/ blurred = cv2.GaussianBlur(image, (11, 11), 0) cv2.imshow("Blurred", blurred) cv2.waitKey(0) # 画框 output = image.copy() cv2.rectangle(output, (320, 60), (420, 160), (0, 0, 255), 2) cv2.imshow("Rectangle", output) cv2.waitKey(0) # 画圆 output = image.copy() cv2.circle(output, (300, 150), 20, (255, 0, 0), -1) cv2.imshow("Circle", output) cv2.waitKey(0) # 划线 output = image.copy() cv2.line(output, (60, 20), (400, 200), (0, 0, 255), 5) cv2.imshow("Line", output) cv2.waitKey(0) # 输出文字 output = image.copy() cv2.putText(output, "https://china-testing.github.io", (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2) cv2.imshow("Text", output) cv2.waitKey(0) 原图: 选取图片区间 ROI (Region of Interest) 缩放 按比例缩放 旋转 使用imutils无损旋转 高斯模糊 画框 画圆 划线 输出文字 执行时的输出 $ python opencv_tutorial_01.py width=600, height=322, depth=3 R=41, G=49, B=37 本节英文原版代码下载 关于旋转这块,实际上pillow做的更好。比如同样逆时针旋转90度。 opencv的实现: import imutils import cv2 image = cv2.imread("jp.png") rotated = imutils.rotate(image, 90) cv2.imshow("Imutils Rotation", rotated) cv2.waitKey(0) pillow的实现: from PIL import Image im = Image.open("jp.png") im2 = im.rotate(90, expand=True) im2.show() 更多参考: python库介绍-图像处理工具pillow中文文档-手册(2018 5.*) 参考资料 技术支持qq群144081101(代码和模型存放) 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 2018最佳人工智能机器学习工具书及下载(持续更新) 代码下载:https://itbooks.pipipan.com/fs/18113597-320636142 代码github地址:https://github.com/china-testing/python-api-tesing/tree/master/opencv_crash_deep_learning 识别俄罗斯方块 # -*- coding: utf-8 -*- # Author: xurongzhong#126.com wechat:pythontesting qq:37391319 # 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入) # qq群:144081101 591302926 567351477 # CreateDate: 2018-11-19 # python opencv_tutorial_02.py --image tetris_blocks.png import argparse import imutils import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Image", image) cv2.waitKey(0) # 转为灰度图 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("Gray", gray) cv2.waitKey(0) # 边缘检测 edged = cv2.Canny(gray, 30, 150) cv2.imshow("Edged", edged) cv2.waitKey(0) # 门限 thresh = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)[1] cv2.imshow("Thresh", thresh) cv2.waitKey(0) # 发现边缘 cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] output = image.copy() # loop over the contours for c in cnts: # draw each contour on the output image with a 3px thick purple # outline, then display the output contours one at a time cv2.drawContours(output, [c], -1, (240, 0, 159), 3) cv2.imshow("Contours", output) cv2.waitKey(0) # draw the total number of contours found in purple text = "I found {} objects!".format(len(cnts)) cv2.putText(output, text, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (240, 0, 159), 2) cv2.imshow("Contours", output) cv2.waitKey(0) # we apply erosions to reduce the size of foreground objects mask = thresh.copy() mask = cv2.erode(mask, None, iterations=5) cv2.imshow("Eroded", mask) cv2.waitKey(0) # 扩大 mask = thresh.copy() mask = cv2.dilate(mask, None, iterations=5) cv2.imshow("Dilated", mask) cv2.waitKey(0) # a typical operation we may want to apply is to take our mask and # apply a bitwise AND to our input image, keeping only the masked # regions mask = thresh.copy() output = cv2.bitwise_and(image, image, mask=mask) cv2.imshow("Output", output) cv2.waitKey(0) 原图和灰度图: 边缘检测 门限 轮廓 查找结果 腐蚀和扩张 屏蔽和位操作 串在一起执行 $ python opencv_tutorial_02.py --image tetris_blocks.png

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

[雪峰磁针石博客]python 3.7极速入门教程9最佳python中文工具书籍下载

筛选了2年内优秀的python书籍,个别经典的书籍扩展到5年内。 尽量只收集通用的书籍,专用的书籍只收集特别优秀者。 python专业书籍汇总 2018最佳人工智能图像处理工具OpenCV书籍下载 流畅的python - 2017.pdf 《流畅的Python》一书致力于帮助Python开发人员挖掘这门语言及相关程序库的优秀特性,避免重复劳动,同时写出简洁、流畅、易读、易维护,并且具有地道Python风格的代码。本书尤其深入探讨了Python语言的高级用法,涵盖数据结构、Python风格的对象、并行与并发,以及元编程等不同的方面。 海报: https://github.com/fluentpython/example-code 2000+ 星 强烈推荐 简明 Python 教程 4nd - 2018.pdf https://github.com/LenKiMo/byte-of-python 近300星 笨办法学Python 3 待上传 本书是一本Python入门书,适合对计算机了解不多,没有学过编程,但对编程感兴趣的读者学习使用。这本书以习题的方式引导读者一步一步学习编程,从简单的打印一直讲到完整项目的实现,让初学者从基础的编程技术入手,最终体验到软件开发的基本过程。本书是基于Python 3.6版本编写的。 本书结构非常简单,除“准备工作”之外,还包括52个习题,其中26个覆盖了输入/输出、变量和函数3个主题,另外26个覆盖了一些比较进阶的话题,如条件判断、循环、类和对象、代码测试及项目的实现等。每一章的格式基本相同,以代码习题开始,按照说明编写代码,运行并检查结果,然后再做附加练习。 Python基础教程(第3版) - 2017.pdf 本书包括Python程序设计的方方面面:首先从Python的安装开始,随后介绍了Python的基础知识和基本概念,包括列表、元组、字符串、字典以及各种语句;然后循序渐进地介绍了一些相对高级的主题,包括抽象、异常、魔法方法、属性、迭代器;此后探讨了如何将Python与数据库、网络、C语言等工具结合使用,从而发挥出Python的强大功能,同时介绍了Python程序测试、打包、发布等知识;最后,作者结合前面讲述的内容,按照实际项目开发的步骤向读者介绍了10个具有实际意义的Python项目的开发过程。 海报: Python基础教程(第3版) - 2018 Beginning Python: From Novice to Professional - 2017 https://github.com/Apress/beginning-python-3ed 100左右星 《Python Cookbook》第三版中文.pdf 《Python Cookbook(第3版)中文版》介绍了Python应用在各个领域中的一些使用技巧和方法,其主题涵盖了数据结构和算法,字符串和文本,数字、日期和时间,迭代器和生成器,文件和I/O,数据编码与处理,函数,类与对象,元编程,模块和包,网络和Web编程,并发,实用脚本和系统管理,测试、调试以及异常,C语言扩展等。本书覆盖了Python应用中的很多常见问题,并提出了通用的解决方案。书中包含了大量实用的编程技巧和示例代码,并在Python 3.3环境下进行了测试,可以很方便地应用到实际项目中去。此外,《Python Cookbook(第3版)中文版》还详细讲解了解决方案是如何工作的,以及为什么能够工作。 《Python Cookbook(第3版)中文版》非常适合具有一定编程基础的Python程序员阅读参考。 Python Cookbook(第3版)(中文版) - 2015 Python Cookbook, 3rd Edition - 2013 https://github.com/dabeaz/python-cookbook 2000左右星 参考资料 讨论qq群144081101 591302926 567351477 钉钉免费群21745728 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 像计算机科学家一样思考Python(下载待上传) 本书以培养读者以计算机科学家一样的思维方式来理解Python语言编程。贯穿全书的主体是如何思考、设计、开发的方法,而具体的编程语言,只是提供了一个具体场景方便介绍的媒介。 全书共21章,详细介绍Python语言编程的方方面面。本书从基本的编程概念开始讲起,包括语言的语法和语义,而且每个编程概念都有清晰的定义,引 领读者循序渐进地学习变量、表达式、语句、函数和数据结构。书中还探讨了如何处理文件和数据库,如何理解对象、方法和面向对象编程,如何使用调试技巧来修正语法错误、运行时错误和语义错误。每一章都配有术语表和练习题,方便读者巩固所学的知识和技巧。此外,每一章都抽出一节来讲解如何调试程序。作者针对每章所专注的语言特性,或者相关的开发问题,总结了调试的方方面面。 本书的第 2版与第 1版相比,做了很多更新,将编程语言从Python 2升级成Python 3,并修改了很多示例和练习,增加了新的章节,更全面地介绍Python语言。 这是一本实用的学习指南,适合没有Python编程经验的程序员阅读,也适合高中或大学的学生、Python爱好者及需要了解编程基础的人阅读。对于首 次接触程序设计的人来说,是一本不可多 得的佳作。 Selenium自动化测试 基于 Python 语言 - 2018.pdf https://github.com/upgundecha/learnsewithpython 星级 低于100 Selenium是一个主要用于Web应用程序自动化测试的工具集合,在行业内已经得到广泛的应用。本书介绍了如何用Python语言调用Selenium WebDriver接口进行自动化测试。主要内容为:基于Python 的 Selenium WebDriver 入门知识、Selenium Python脚本、使用unittest 编写单元测试、生成HTML格式的测试报告、元素定位、Selenium Python API 介绍、元素等待机制、跨浏览器测试、移动端测试、编写一个iOS测试脚本、编写一个Android测试脚本、Page Object与数据驱动测试、Selenium WebDriver的特性、第三方工具与框架集成等核心技术。 《Selenium自动化测试 基于Python语言》适合任何软件测试人员阅读,也适合作为大专院校师生的学习用书和培训学校的教材。 -- 本书虽然为2018年翻译,但是实际基于selenium2和python2,已经过时,很多实例已经不能运行。阅读时可参考 selenium自动化测试工具python笔试面试项目实战5键盘操作,尽管有点过时,依旧是selenium书籍中的佳品。 对应的英文版:Learning Selenium Testing Tools with Python - 2014.pdf Python网络数据采集 Python网络数据采集 - 2016.pdf 本书采用简洁强大的Python语言,介绍了网络数据采集,并为采集新式网络中的各种数据类型提供了全面的指导。第 1部分重点介绍网络数据采集的基本原理:如何用Python从网络服务器请求信息,如何对服务器的响应进行基本处理,以及如何以自动化手段与网站进行交互。第 二部分介绍如何用网络爬虫测试网站,自动化处理,以及如何通过更多的方式接入网络。 Web Scraping with Python 2nd - 2018.pdf https://github.com/REMitchell/python-scraping 2000左右星 其他书籍 Head First Python 2nd 暂时没找到文字的电子书

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

[雪峰磁针石博客]数据分析工具pandas快速入门教程5-处理缺失数据

第5章 缺失数据 介绍 很少没有任何缺失值的数据集。 有许多缺失数据的表示。 在数据库中是NULL值,一些编程语言使用NA。缺失值可以是空字符串:''或者甚至是数值88或99等。Pandas显示缺失值为NaN。 本章将涵盖: 什么是缺失值 如何创建缺失值 如何重新编码并使用缺失值进行计算 什么是缺失值 可以从numpy中获得NaN值,在Python中看到缺失值使用几种方式显示:NaN,NAN或nan,他们都是相等的。 NaN不等于0或空字符串''。 In [1]: from numpy import NaN, NAN, nan In [2]: print(NaN == True, NaN == False, NaN == 0, NaN == '', sep='|') False|False|False|False In [3]: print(NaN == NaN, NaN == nan, NaN == NAN, nan == NAN, sep='|') False|False|False|False In [4]: import pandas as pd In [5]: print(pd.isnull(NaN), pd.isnull(nan), pd.isnull(NAN), sep='|') True|True|True In [6]: print(pd.notnull(NaN), pd.notnull(99), pd.notnull("https://china-testing.github.io"), sep='|') False|True|True 缺失值的来源 来自加载数据或数据处理 加载数据 当我们加载数据时,pandas会自动找到该缺少数据的单元格,并填充NaN值。在read_csv函数中,参数na_values, keep_default_na, na_filter用于处理缺失值。比如:na_values=[99]。na_filter设置为False,在读大文件时会提升性能。 5-1.py import pandas as pd visited_file = 'data/survey_visited.csv' print(pd.read_csv(visited_file)) print(pd.read_csv(visited_file, keep_default_na=False)) print(pd.read_csv(visited_file, na_values=[''], keep_default_na=False)) 执行结果 $ python3 5-1.py ident site dated 0 619 DR-1 1927-02-08 1 622 DR-1 1927-02-10 2 734 DR-3 1939-01-07 3 735 DR-3 1930-01-12 4 751 DR-3 1930-02-26 5 752 DR-3 NaN 6 837 MSK-4 1932-01-14 7 844 DR-1 1932-03-22 ident site dated 0 619 DR-1 1927-02-08 1 622 DR-1 1927-02-10 2 734 DR-3 1939-01-07 3 735 DR-3 1930-01-12 4 751 DR-3 1930-02-26 5 752 DR-3 6 837 MSK-4 1932-01-14 7 844 DR-1 1932-03-22 ident site dated 0 619 DR-1 1927-02-08 1 622 DR-1 1927-02-10 2 734 DR-3 1939-01-07 3 735 DR-3 1930-01-12 4 751 DR-3 1930-02-26 5 752 DR-3 NaN 6 837 MSK-4 1932-01-14 7 844 DR-1 1932-03-22 合并数据 import pandas as pd visited = pd.read_csv('data/survey_visited.csv') survey = pd.read_csv('data/survey_survey.csv') print(visited) print(survey) vs = visited.merge(survey, left_on='ident', right_on='taken') print(vs) 执行结果 $ python3 5-2.py ident site dated 0 619 DR-1 1927-02-08 1 622 DR-1 1927-02-10 2 734 DR-3 1939-01-07 3 735 DR-3 1930-01-12 4 751 DR-3 1930-02-26 5 752 DR-3 NaN 6 837 MSK-4 1932-01-14 7 844 DR-1 1932-03-22 taken person quant reading 0 619 dyer rad 9.82 1 619 dyer sal 0.13 2 622 dyer rad 7.80 3 622 dyer sal 0.09 4 734 pb rad 8.41 5 734 lake sal 0.05 6 734 pb temp -21.50 7 735 pb rad 7.22 8 735 NaN sal 0.06 9 735 NaN temp -26.00 10 751 pb rad 4.35 11 751 pb temp -18.50 12 751 lake sal 0.10 13 752 lake rad 2.19 14 752 lake sal 0.09 15 752 lake temp -16.00 16 752 roe sal 41.60 17 837 lake rad 1.46 18 837 lake sal 0.21 19 837 roe sal 22.50 20 844 roe rad 11.25 ident site dated taken person quant reading 0 619 DR-1 1927-02-08 619 dyer rad 9.82 1 619 DR-1 1927-02-08 619 dyer sal 0.13 2 622 DR-1 1927-02-10 622 dyer rad 7.80 3 622 DR-1 1927-02-10 622 dyer sal 0.09 4 734 DR-3 1939-01-07 734 pb rad 8.41 5 734 DR-3 1939-01-07 734 lake sal 0.05 6 734 DR-3 1939-01-07 734 pb temp -21.50 7 735 DR-3 1930-01-12 735 pb rad 7.22 8 735 DR-3 1930-01-12 735 NaN sal 0.06 9 735 DR-3 1930-01-12 735 NaN temp -26.00 10 751 DR-3 1930-02-26 751 pb rad 4.35 11 751 DR-3 1930-02-26 751 pb temp -18.50 12 751 DR-3 1930-02-26 751 lake sal 0.10 13 752 DR-3 NaN 752 lake rad 2.19 14 752 DR-3 NaN 752 lake sal 0.09 15 752 DR-3 NaN 752 lake temp -16.00 16 752 DR-3 NaN 752 roe sal 41.60 17 837 MSK-4 1932-01-14 837 lake rad 1.46 18 837 MSK-4 1932-01-14 837 lake sal 0.21 19 837 MSK-4 1932-01-14 837 roe sal 22.50 20 844 DR-1 1932-03-22 844 roe rad 11.25 用户输入 import pandas as pd from numpy import NaN, NAN, nan num_legs = pd.Series({'goat': 4, 'amoeba': nan}) print(num_legs) scientists = pd.DataFrame({'Name': ['Rosaline Franklin', 'William Gosset'], 'Occupation': ['Chemist', 'Statistician'], 'Born': ['1920-07-25', '1876-06-13'], 'Died': ['1958-04-16', '1937-10-16'], 'missing': [NaN, nan]}) print(scientists) scientists['missing'] = nan print(scientists) 执行结果 $ python3 5-3.py amoeba NaN goat 4.0 dtype: float64 Born Died Name Occupation missing 0 1920-07-25 1958-04-16 Rosaline Franklin Chemist NaN 1 1876-06-13 1937-10-16 William Gosset Statistician NaN Born Died Name Occupation missing 0 1920-07-25 1958-04-16 Rosaline Franklin Chemist NaN 1 1876-06-13 1937-10-16 William Gosset Statistician NaN 重新索引 5-4.py import pandas as pd from numpy import NaN, NAN, nan gapminder = pd.read_csv('data/gapminder.tsv', sep='\t') life_exp = gapminder.groupby(['year'])['lifeExp'].mean() print(life_exp) print(life_exp.reindex(range(2000, 2010))) 执行结果 year 1952 49.057620 1957 51.507401 1962 53.609249 1967 55.678290 1972 57.647386 1977 59.570157 1982 61.533197 1987 63.212613 1992 64.160338 1997 65.014676 2002 65.694923 2007 67.007423 Name: lifeExp, dtype: float64 year 2000 NaN 2001 NaN 2002 65.694923 2003 NaN 2004 NaN 2005 NaN 2006 NaN 2007 67.007423 2008 NaN 2009 NaN Name: lifeExp, dtype: float64 处理缺失数据 统计缺失数据 5-5.py import pandas as pd from numpy import NaN, NAN, nan import numpy as np ebola = pd.read_csv('data/country_timeseries.csv') print(ebola.head()) print(ebola.count()) num_rows = ebola.shape[0] print("num_rows") print(num_rows) num_missing = num_rows - ebola.count() print("num_missing:") print(num_missing) print(np.count_nonzero(ebola.isnull())) print(np.count_nonzero(ebola['Cases_Guinea'].isnull())) print(ebola.Cases_Guinea.value_counts(dropna=False).head()) 执行结果 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone \ 0 1/5/2015 289 2776.0 NaN 10030.0 1 1/4/2015 288 2775.0 NaN 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 NaN 8157.0 NaN 4 12/31/2014 284 2730.0 8115.0 9633.0 Cases_Nigeria Cases_Senegal Cases_UnitedStates Cases_Spain Cases_Mali \ 0 NaN NaN NaN NaN NaN 1 NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN NaN 3 NaN NaN NaN NaN NaN 4 NaN NaN NaN NaN NaN Deaths_Guinea Deaths_Liberia Deaths_SierraLeone Deaths_Nigeria \ 0 1786.0 NaN 2977.0 NaN 1 1781.0 NaN 2943.0 NaN 2 1767.0 3496.0 2915.0 NaN 3 NaN 3496.0 NaN NaN 4 1739.0 3471.0 2827.0 NaN Deaths_Senegal Deaths_UnitedStates Deaths_Spain Deaths_Mali 0 NaN NaN NaN NaN 1 NaN NaN NaN NaN 2 NaN NaN NaN NaN 3 NaN NaN NaN NaN 4 NaN NaN NaN NaN Date 122 Day 122 Cases_Guinea 93 Cases_Liberia 83 Cases_SierraLeone 87 Cases_Nigeria 38 Cases_Senegal 25 Cases_UnitedStates 18 Cases_Spain 16 Cases_Mali 12 Deaths_Guinea 92 Deaths_Liberia 81 Deaths_SierraLeone 87 Deaths_Nigeria 38 Deaths_Senegal 22 Deaths_UnitedStates 18 Deaths_Spain 16 Deaths_Mali 12 dtype: int64 num_rows 122 num_missing: Date 0 Day 0 Cases_Guinea 29 Cases_Liberia 39 Cases_SierraLeone 35 Cases_Nigeria 84 Cases_Senegal 97 Cases_UnitedStates 104 Cases_Spain 106 Cases_Mali 110 Deaths_Guinea 30 Deaths_Liberia 41 Deaths_SierraLeone 35 Deaths_Nigeria 84 Deaths_Senegal 100 Deaths_UnitedStates 104 Deaths_Spain 106 Deaths_Mali 110 dtype: int64 1214 29 NaN 29 86.0 3 495.0 2 112.0 2 390.0 2 Name: Cases_Guinea, dtype: int64 处理缺失数据 5-6.py import pandas as pd from numpy import NaN, NAN, nan import numpy as np ebola = pd.read_csv('data/country_timeseries.csv') print(ebola.iloc[0:10, 0:5]) print(ebola.fillna(0).iloc[0:10, 0:5]) # 前向填充 print(ebola.fillna(method='ffill').iloc[0:10, 0:5]) # 后向填充 print(ebola.fillna(method='bfill').iloc[0:10, 0:5]) print(ebola.interpolate().iloc[0:10, 0:5]) print(ebola.shape) ebola_dropna = ebola.dropna() print(ebola_dropna.shape) print(ebola_dropna) ebola['Cases_multiple'] = ebola['Cases_Guinea'] + ebola['Cases_Liberia'] + \ ebola['Cases_SierraLeone'] ebola_subset = ebola.loc[:, ['Cases_Guinea', 'Cases_Liberia', 'Cases_SierraLeone', 'Cases_multiple']] print(ebola_subset.head(n=10)) print(ebola.Cases_Guinea.sum(skipna = True)) print(ebola.Cases_Guinea.sum(skipna = False)) 执行结果 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone 0 1/5/2015 289 2776.0 NaN 10030.0 1 1/4/2015 288 2775.0 NaN 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 NaN 8157.0 NaN 4 12/31/2014 284 2730.0 8115.0 9633.0 5 12/28/2014 281 2706.0 8018.0 9446.0 6 12/27/2014 280 2695.0 NaN 9409.0 7 12/24/2014 277 2630.0 7977.0 9203.0 8 12/21/2014 273 2597.0 NaN 9004.0 9 12/20/2014 272 2571.0 7862.0 8939.0 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone 0 1/5/2015 289 2776.0 0.0 10030.0 1 1/4/2015 288 2775.0 0.0 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 0.0 8157.0 0.0 4 12/31/2014 284 2730.0 8115.0 9633.0 5 12/28/2014 281 2706.0 8018.0 9446.0 6 12/27/2014 280 2695.0 0.0 9409.0 7 12/24/2014 277 2630.0 7977.0 9203.0 8 12/21/2014 273 2597.0 0.0 9004.0 9 12/20/2014 272 2571.0 7862.0 8939.0 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone 0 1/5/2015 289 2776.0 NaN 10030.0 1 1/4/2015 288 2775.0 NaN 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 2769.0 8157.0 9722.0 4 12/31/2014 284 2730.0 8115.0 9633.0 5 12/28/2014 281 2706.0 8018.0 9446.0 6 12/27/2014 280 2695.0 8018.0 9409.0 7 12/24/2014 277 2630.0 7977.0 9203.0 8 12/21/2014 273 2597.0 7977.0 9004.0 9 12/20/2014 272 2571.0 7862.0 8939.0 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone 0 1/5/2015 289 2776.0 8166.0 10030.0 1 1/4/2015 288 2775.0 8166.0 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 2730.0 8157.0 9633.0 4 12/31/2014 284 2730.0 8115.0 9633.0 5 12/28/2014 281 2706.0 8018.0 9446.0 6 12/27/2014 280 2695.0 7977.0 9409.0 7 12/24/2014 277 2630.0 7977.0 9203.0 8 12/21/2014 273 2597.0 7862.0 9004.0 9 12/20/2014 272 2571.0 7862.0 8939.0 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone 0 1/5/2015 289 2776.0 NaN 10030.0 1 1/4/2015 288 2775.0 NaN 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 2749.5 8157.0 9677.5 4 12/31/2014 284 2730.0 8115.0 9633.0 5 12/28/2014 281 2706.0 8018.0 9446.0 6 12/27/2014 280 2695.0 7997.5 9409.0 7 12/24/2014 277 2630.0 7977.0 9203.0 8 12/21/2014 273 2597.0 7919.5 9004.0 9 12/20/2014 272 2571.0 7862.0 8939.0 (122, 18) (1, 18) Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone \ 19 11/18/2014 241 2047.0 7082.0 6190.0 Cases_Nigeria Cases_Senegal Cases_UnitedStates Cases_Spain Cases_Mali \ 19 20.0 1.0 4.0 1.0 6.0 Deaths_Guinea Deaths_Liberia Deaths_SierraLeone Deaths_Nigeria \ 19 1214.0 2963.0 1267.0 8.0 Deaths_Senegal Deaths_UnitedStates Deaths_Spain Deaths_Mali 19 0.0 1.0 0.0 6.0 Cases_Guinea Cases_Liberia Cases_SierraLeone Cases_multiple 0 2776.0 NaN 10030.0 NaN 1 2775.0 NaN 9780.0 NaN 2 2769.0 8166.0 9722.0 20657.0 3 NaN 8157.0 NaN NaN 4 2730.0 8115.0 9633.0 20478.0 5 2706.0 8018.0 9446.0 20170.0 6 2695.0 NaN 9409.0 NaN 7 2630.0 7977.0 9203.0 19810.0 8 2597.0 NaN 9004.0 NaN 9 2571.0 7862.0 8939.0 19372.0 84729.0 nan 参考资料 技术支持qq群144081101 591302926 567351477 钉钉免费群21745728 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 源码下载 本文英文版书籍下载

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

[雪峰磁针石博客]flask构建自动化测试平台6-交互式犯罪地图

6-交互式犯罪地图 本章将介绍以下主题: mysql 创建犯罪地图 本文最新版本 代码地址 安装mysql # apt-get install mysql-server # pip3 install pymysql # python db_setup.py # 创建数据库 dbconfig.py test = False db_user = 'root' db_password = '654321_' db_setup.py import pymysql import dbconfig connection = pymysql.connect(host='localhost', user=dbconfig.db_user, passwd=dbconfig.db_password) try: with connection.cursor() as cursor: sql = "CREATE DATABASE IF NOT EXISTS crimemap" cursor.execute(sql) sql = """CREATE TABLE IF NOT EXISTS crimemap.crimes ( id int NOT NULL AUTO_INCREMENT, latitude FLOAT(10,6), longitude FLOAT(10,6), date DATETIME, category VARCHAR(50), description VARCHAR(255), updated_at TIMESTAMP, PRIMARY KEY (id) )""" cursor.execute(sql) connection.commit() finally: connection.close() crimemap.py from dbhelper import DBHelper from flask import Flask from flask import render_template from flask import request app = Flask(__name__) DB = DBHelper() @app.route("/") def home(): try: data = DB.get_all_inputs() except Exception as e: print(e) data = None return render_template("home.html", data=data) @app.route("/add", methods=["POST"]) def add(): try: data = request.form.get("userinput") DB.add_input(data) except Exception as e: print(e) return home() @app.route("/clear") def clear(): try: DB.clear_all() except Exception as e: print(e) return home() if __name__ == '__main__': app.run(host='0.0.0.0',port=8000, debug=True) dbhelper.py import pymysql import dbconfig class DBHelper: def connect(self, database="crimemap"): return pymysql.connect(host='localhost', user=dbconfig.db_user, passwd=dbconfig.db_password, db=database) def get_all_inputs(self): connection = self.connect() try: query = "SELECT description FROM crimes;" with connection.cursor() as cursor: cursor.execute(query) return cursor.fetchall() finally: connection.close() def add_input(self, data): connection = self.connect() try: query = "INSERT INTO crimes (description) VALUES (%s);" with connection.cursor() as cursor: cursor.execute(query, data) connection.commit() finally: connection.close() def clear_all(self): connection = self.connect() try: query = "DELETE FROM crimes;" with connection.cursor() as cursor: cursor.execute(query) connection.commit() finally: connection.close() home.html <html> <body> <head> <title>Crime Map</title> </head> <h1>Crime Map</h1> <form action="/add" method="POST"> <input type="text" name="userinput"> <input type="submit" value="Submit"> </form> <a href="/clear">clear</a> {% for userinput in data %} <p>{{userinput}}</p> {% endfor %} </body> </html> 参考资料 本文相关书籍下载 讨论 钉钉免费群21745728 qq群144081101 567351477 本文涉及的python测试开发库 谢谢点赞! 本文代码地址

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

[雪峰磁针石博客]python库介绍-os.path: 平台独立的文件名操作

Title: python库介绍-os.path: 平台独立的文件名操作Date: 2018-03-25 19:20Category: pythonSlug: python3_lib_os.path 目的:文件名和路径解析,组合,测试等。 使用os.path模块中包含的函数编写代码以便在多个平台上处理文件非常简单。即使不打算在平台之间移植的程序也应该使用os.path来进行可靠的文件名解析。 解析路径 路径解析依赖于在os中定义的几个变量: os.sep - 路径各部分之间的分隔符(例如“/”或“\”)。 os.extsep - 文件名和文件扩展名之间的分隔符。 os.pardir - 上级目录(e.g., “..”)。 os.curdir - 当前目录 (e.g., “.”)。 split()函数将路径分成两个独立的部分,并返回包含结果的元组。元组的第二个元素是路径的最后一个元素,第一个元素是之前的所有元素。 # ospath_split.py import os.path PATHS = [ '/one/two/three', '/one/two/three/', '/', '.', '', ] for path in PATHS: print('{!r:>17} : {}'.format(path, os.path.split(path))) 执行结果 $ python3 ospath_split.py '/one/two/three' : ('/one/two', 'three') '/one/two/three/' : ('/one/two/three', '') '/' : ('/', '') '.' : ('', '.') '' : ('', '') basename()函数返回等价于split()第二部分的值。 import os.path PATHS = [ '/one/two/three', '/one/two/three/', '/', '.', '', ] for path in PATHS: print('{!r:>17} : {!r}'.format(path, os.path.basename(path))) 执行结果 $ python3 ospath_basename.py '/one/two/three' : 'three' '/one/two/three/' : '' '/' : '' '.' : '.' '' : '' 完整路径被分解到最后一个元素,无论是指文件还是目录。如果路径在目录分隔符(os.sep)中结束,则basename是空的。 dirname() 函数返回分割路径的第一部分: import os.path PATHS = [ '/one/two/three', '/one/two/three/', '/', '.', '', ] for path in PATHS: print('{!r:>17} : {!r}'.format(path, os.path.dirname(path))) 执行结果 $ python3 ospath_dirname.py '/one/two/three' : '/one/two' '/one/two/three/' : '/one/two/three' '/' : '/' '.' : '' '' : '' 将basename()的结果与dirname()结合起来得到原始路径。 splitext()工作方式类似于split(),但将扩展分隔符(而不是目录分隔符)的路径分开。 import os.path PATHS = [ 'filename.txt', 'filename', '/path/to/filename.txt', '/', '', 'my-archive.tar.gz', 'no-extension.', ] for path in PATHS: print('{!r:>21} : {!r}'.format(path, os.path.splitext(path))) 执行结果 $ python3 ospath_splitext.py 'filename.txt' : ('filename', '.txt') 'filename' : ('filename', '') '/path/to/filename.txt' : ('/path/to/filename', '.txt') '/' : ('/', '') '' : ('', '') 'my-archive.tar.gz' : ('my-archive.tar', '.gz') 'no-extension.' : ('no-extension', '.') 在查找扩展名时,只使用最后一次出现的os.extsep,所以如果文件名有多个扩展名,则将其分割结果保留在前缀的一部分。 commonprefix() 将路径列表作为参数,并返回表示所有路径中存在的公共前缀的单个字符串。该值可能表示实际上不存在的路径,并且路径分隔符不包含在考虑因素中,所以前缀可能不会停止在分隔符边界上。 import os.path paths = ['/one/two/three/four', '/one/two/threefold', '/one/two/three/', ] for path in paths: print('PATH:', path) print() print('PREFIX:', os.path.commonprefix(paths)) 执行结果 $ python3 ospath_commonprefix.py PATH: /one/two/three/four PATH: /one/two/threefold PATH: /one/two/three/ PREFIX: /one/two/three commonpath()则会考虑os.seq。 import os.path paths = ['/one/two/three/four', '/one/two/threefold', '/one/two/three/', ] for path in paths: print('PATH:', path) print() print('PREFIX:', os.path.commonpath(paths)) 执行结果 $ python3 ospath_commonpath.py PATH: /one/two/three/four PATH: /one/two/threefold PATH: /one/two/three/ PREFIX: /one/two 本文代码地址 本文最新版本地址 交流QQ群:python 测试开发 144081101 构建路径 除了将现有的路径分开之外,通常还需要从其他字符串构建路径。要将多个路径组件合并请使用join(): import os.path PATHS = [ ('one', 'two', 'three'), ('/', 'one', 'two', 'three'), ('/one', '/two', '/three'), ] for parts in PATHS: print('{} : {!r}'.format(parts, os.path.join(*parts))) 执行结果 $ python3 ospath_join.py ('one', 'two', 'three') : 'one/two/three' ('/', 'one', 'two', 'three') : '/one/two/three' ('/one', '/two', '/three') : '/three' 如果任何连接的参数以os.sep开始,则所有先前的参数都将被丢弃,新的参数将成为返回值的开始。 也可以使用包含可自动扩展的“可变”组件的路径。例如,expanduser() 将 ~转换为用户主目录的名称。 # ospath_expanduser.py import os.path for user in ['', 'andrew', 'nosuchuser']: lookup = '~' + user print('{!r:>15} : {!r}'.format( lookup, os.path.expanduser(lookup))) 执行结果 '~' : '/home/andrew' '~andrew' : '/home/andrew' '~nosuchuser' : '~nosuchuser' 如果找不到用户的主目录,则字符串将以不变的形式返回,如本示例中的〜nosuchuser一样。 expandvars()更通用,它展开路径中的所有shell环境变量。 # ospath_expandvars.py import os.path import os os.environ['MYVAR'] = 'VALUE' print(os.path.expandvars('/path/to/$MYVAR')) 执行结果 $ python3 ospath_expandvars.py /path/to/VALUE 规范化路径 使用join()或嵌入变量从不同的字符串汇编的路径可能会以额外的分隔符或相对路径组件结束。使用normpath()来清理它们: # ospath_normpath.py import os.path PATHS = [ 'one//two//three', 'one/./two/./three', 'one/../alt/two/three', ] for path in PATHS: print('{!r:>22} : {!r}'.format(path, os.path.normpath(path))) 执行结果 $ python3 ospath_normpath.py 'one//two//three' : 'one/two/three' 'one/./two/./three' : 'one/two/three' 'one/../alt/two/three' : 'alt/two/three' 要将相对路径转换为绝对文件名,请使用abspath()。 # ospath_abspath.py import os import os.path os.chdir('/usr') PATHS = [ '.', '..', './one/two/three', '../one/two/three', ] for path in PATHS: print('{!r:>21} : {!r}'.format(path, os.path.abspath(path))) 执行结果 $ python3 ospath_normpath.py 'one//two//three' : 'one/two/three' 'one/./two/./three' : 'one/two/three' 'one/../alt/two/three' : 'alt/two/three' 文件时间 除了使用路径之外,os.path还包括用于检索文件属性的函数,类似于os.stat()返回的函数: import os.path import time print('File :', __file__) print('Access time :', time.ctime(os.path.getatime(__file__))) print('Modified time:', time.ctime(os.path.getmtime(__file__))) print('Change time :', time.ctime(os.path.getctime(__file__))) print('Size :', os.path.getsize(__file__)) os.path.getatime()返回访问时间,os.path.getmtime()返回修改时间,os.path.getctime()返回创建时间。 os.path.getsize()返回文件中的数据量,用字节表示。 执行结果 $ python3 ospath_properties.py File : ospath_properties.py Access time : Fri Aug 26 16:38:05 2016 Modified time: Fri Aug 26 15:50:48 2016 Change time : Fri Aug 26 15:50:49 2016 Size : 481 测试文件 当程序遇到路径名时,通常需要知道路径是指文件,目录还是符号链接,以及是否存在。 os.path包含测试所有这些条件的函数。 import os.path FILENAMES = [ __file__, os.path.dirname(__file__), '/', './broken_link', ] for file in FILENAMES: print('File : {!r}'.format(file)) print('Absolute :', os.path.isabs(file)) print('Is File? :', os.path.isfile(file)) print('Is Dir? :', os.path.isdir(file)) print('Is Link? :', os.path.islink(file)) print('Mountpoint? :', os.path.ismount(file)) print('Exists? :', os.path.exists(file)) print('Link Exists?:', os.path.lexists(file)) print() 执行结果 $ ln -s /does/not/exist broken_link $ python3 ospath_tests.py File : 'ospath_tests.py' Absolute : False Is File? : True Is Dir? : False Is Link? : False Mountpoint? : False Exists? : True Link Exists?: True File : '' Absolute : False Is File? : False Is Dir? : False Is Link? : False Mountpoint? : False Exists? : False Link Exists?: False File : '/' Absolute : True Is File? : False Is Dir? : True Is Link? : False Mountpoint? : True Exists? : True Link Exists?: True File : './broken_link' Absolute : False Is File? : False Is Dir? : False Is Link? : True Mountpoint? : False Exists? : False Link Exists?: True 参考资料 本文最新版本地址 讨论 钉钉免费群21745728 qq群144081101 567351477 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载

资源下载

更多资源
Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

WebStorm

WebStorm

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

用户登录
用户注册