首页 文章 精选 留言 我的

精选列表

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

基于百度飞桨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测试开发库 谢谢点赞! 本文相关海量书籍下载

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

阿里云轻量应用服务器,5分钟搭建wordpress个人博客

大家好,今天的博文,给大家介绍阿里云轻量服务器使用。首先,轻量服务器目前只支持linux系统,而博主只是个windows用户,因此在阿里云轻量服务器内测期,并没有对轻量服务器来兴趣。一直到内测送的体验券到期前两天,才懒散的按照官方文档试了一把。这一体验,感觉还不错,居然只需要2个命令即可上手。 具体操作进行之前,先把我的幸运券发给大家,20种产品首购可打折和享受优惠 【领券】http://wzfw.ltd/qjyl 【购买】轻量应用服务器http://wzfw.ltd/sas(本文重点) ECS,新用户独享199元一年http://wzfw.ltd/ecs199 ECS,新老用户3种自选一http://wzfw.ltd/ecs330 【抽奖】ECS首购大于百元http://wzfw.ltd/jiang 推荐结束,请看我下面的步骤: 1,领券选配购买(图1、2、3) 2,找管理台,由于是新机型,因此现在并不容易直接找到(图4) 3,轻量应用服务器,控制台介绍(图5、6) 4,开始配置,2个命令即可。其实只用第一个也行,拿到wordPress管理密码即可。(图7、8) 5,服务器配置完成,剩下的只需要登录WordPress后台配置即可(图9、10) 6,最终效果(图11) 原文地址:https://www.opengps.cn/Blog/View.aspx?id=40,文章的更新编辑依此链接为准。欢迎关注源站原创文章!

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

【博客大赛】+移动端4位/6位验证码/密码输入框H5实现

阶段一、六位验证码输入框 先贴图,需要实现的效果是这样的。 实现思路有两个: 1、用6个input,输入一个数字后将focus给下一个输入框。 2、用一个input和6个span,input隐藏,用span显示。 现在大部分都是使用的第二种方法。 两种方案遇到的坑,以及优缺点,如下: 方案一:6个input。 主要就是用js切换focus,在安卓是相当流畅的,但是在ios会严重卡顿,简直逼死强迫症。 HTML: JS: functioninputNext(id){//传过来的id是个对象 varindex=Number(id.id.split("_")[1]) if(id.value.length<1){//删除 id.value='' if(index>1){ varpreId='check_'+Number(Number(index)-1) document.getElementById(preId).focus() returnfalse } }else{ if(id.value.length>1){ varnextValue=id.value.slice(1,2) varnextId='check_'+Number(Number(index)+1) id.value=id.value.slice(0,1) if((index+1)<=6){ document.getElementById(nextId).value=nextValue document.getElementById(nextId).focus() } } } } PS:我这里写的删除方法是有问题的,这也是我果断放弃这种方案的原因之一。 如果正常输入,然后删除是可以的。 但是输入几个数后,先点击中间的框删除一个数字,再回到最后,便只能将中间到最后的这几个删掉,最前面的还需要手动点一下得到focus才能删除。 这对用户来说,简直太不友好了。。。 CSS: .divYZM{ width:90%; margin:0auto; height:100px; background-color:rgba(74,35,35,0.42); } .numDiv{ display:block; width:10%; float:left; border-radius:5px; text-align:center; line-height:60px; font-size:20px; font-weight:900; color:red; background-color:white; height:60px; border:0; padding:0; margin:0; margin-left:5.7%; top:20px; position:relative; caret-color:transparent; } 这里遇到的坑,举一个栗子。 input限制长度的属性maxlength a、与如下两种配合使用(tel也可以限制) 或者 b、当type为number时不起作用。这时需要用js控制。 注意:此外,tel类型的input在ios上会调出全数字键盘,而number类型的input则会调出带有标点符号的键盘。 方案二:1个input和6个span。 隐藏input,用span显示内容。大坑就是,何种情况下能调起ios的软键盘呢? 先贴一下我刚开始的input样式。 width:0; height:0; border:0; padding:0; margin:0; 第二种 display:none; 简单粗暴,结果就是,ios木得反应。为啥呢,我想不通。 后来在晚上睡觉的时候我在想,我这两种方式input都么有占位啊,那是不是占位了就可以了呢? 经测果然是可以的(默默谴责自己懒了一下,没有将不隐藏input的情况,在手机上进行测试)。 但是这里要注意一点,input占位建议写成宽度占位,如果是高度占位,width为0时,会出现输入1234,显示为4321这种情况,光标默认在最前,且用js手动挪动光标到最后也是不起效果的。例如,类似代码我设置了宽度为0,且使用了如下方法挪动光标到最后,以解决输入1234,显示4321的问题。完全没得作用。后来突然想到是不是因为宽度为0。给input加了宽度才正常显示了。 错误代码示例:宽度为0 input的样式: #yzm{ width:0; border:0; padding:0; margin:0; height:.44rem; position:absolute; outline:none; color:transparent; text-shadow:000transparent; margin-left:-100%; } 对应的挪动光标的方法: lettObj=document.getElementById("#yzm"); letlen=tObj.value.length; if(tObj.setSelectionRange){ tObj.setSelectionRange(len,len); tObj.focus(); }elseif(tObj.createTextRange){ varrng=tObj.createTextRange(); rng.move('character',len); rng.select(); } 接下来贴正确代码。 CSS: #yzm{ width:90%; height:.44rem; border:0; padding:0; margin:0; margin-left:-100%; outline:none; color:transparent; text-shadow:000transparent; position:absolute; } #yzmTable{ width:90%; height:100px; margin:0auto; background-color:rgb(441212/93%); border-radius:5px; } #yzmTablespan{ display:block; width:10%; height:60px; float:left; border-radius:5px; text-align:center; line-height:60px; font-size:20px; font-weight:900; color:red; background-color:white; margin-left:5.7%; top:20px; position:relative; } 这里对input的样式也包括对光标的隐藏,我在第一种方案中对光标未进行处理,因为在看到ios的卡卡卡之后果断放弃了第一种方案。 HTML: JS: functionintoYzm(index){ varele=document.getElementById("yzm") ele.focus() } functionyzmInsert(){//input内容改变时触发 for(vari=1;i<=6;i++){ varnextId='s_'+i document.getElementById(nextId).innerHTML='' } varyzm=document.getElementById("yzm").value varyzmArr=yzm.split(''); for(vari=0;i<yzmArr.length;i++){ constnum=yzmArr[i]; varid='s_'+Number(i+1) document.getElementById(id).innerHTML=''+num+'' } } //收起软键盘的方法,点击除了输入框之外的其他区域就收起软键盘 $('body').on('touchend',function(el){ if(el.target.tagName!='SPAN'){ $('yzm').blur() } }) 在第二种方案中有两个地方注意下: a、在js方法中加了对全局中6个span标签(即六个输入框)之外区域点击事件的监听,用以收起软键盘,方法如下。 $('body').on('touchend',function(el){ if(el.target.tagName!='SPAN'){ $('yzm').blur() } }) (比较粗糙,如果页面中还有别的部分就比较受影响了,可以自行改进) b、在隐藏的input中添加了onclick方法,如下并且在其中用了blur方法使得此输入框失去焦点。为什么这么做呢? 因为此处的隐藏并非真正的隐藏,而是透明化处理,边框包括光标全部透明化,但实际上它还是占位的,所以当你点击输入框上方空白处时,仍会唤起软键盘,就和我们之前所想的点击输入框之外区域就收起软键盘冲突了。 因此将input自身的点击获取focus禁止掉,就OK了。 阶段二、四位验证码输入框 pia效果图 基本上是基于以上 阶段一、六位验证码输入方式(以下统称“阶段一”) 的后期填坑 这是仿照“阶段一”又新写了个验证码的小页面,有些微的不同 输入编号后四位,可能有X字母,所以隐藏input的type不能设置为number了,懒惰的我直接删掉了type属性(造坑开始) 且因为上次研究时漏掉了一些知识点,也造了一波坑,以下一一列举。 问题1、四位空格输入,1234,但是每次输入下一个数字,前面的内容都会整体向后移动,输完结果是4321;且输入一半点删除没反应。还得输入总共五位数字才能删除 ??!我懵了,input给显示的几个span的赋值方式(见“阶段一”的js代码)是一样样的呀,怎么回事 debug发现隐藏的input值就已经是4321了,所以不是赋值方法的问题,以下是有问题的隐藏input的样式: #IdentifyNoCheckInput{ width:0; border:0; padding:0; margin:0; height:10px; position:absolute; top:-11px; outline:none; color:transparent; text-shadow:000transparent; } 最初怀疑是光标自动到了最前面导致的,使用了百度的手动移动光标方法,并不管用。 对比“阶段一”中隐藏input的样式,可以发现本次宽度设成了0,有高度(高度随意,只要不挡住别的元素显示就行),有宽度或高度是为了占位,能唤起软键盘。 而“阶段一”中是有宽度的,这个差别引起了我的怀疑。为以上样式新增两条 width:100%; margin-left:-100%; 再进行输入,正常了,输入1234就显示1234,也不会有删不掉的情况存在了。 第一个坑填坑完毕。 总结:设置宽度高度是为了占位,从而唤起软键盘。有高度或有宽度就可以,但是建议设置宽度,以免发生输入内容反转的情况。 问题2、部分ios手机无法正常唤起软键盘 在测试的时候,手机型号就那几个,大家测得顺顺当当。上线之后就报了好多ios无法正常输入的问题。 问题版本如下: 苹果p8,苹果6+(系统版本10),苹果6pok(系统版本11.4.1)和苹果6p plus(系统版本12.4.8) 以下是隐藏input的代码: 最初思路跑偏,开始各种查版本兼容的方法,但是没有合适的解决方案。 后在老大的提醒下,既然上篇文章中的验证码没有报这个问题,这个也不应该有问题啊。 对比发现就是少了个type,就想到是不是缺少type导致的,加了个type="text" emmmm,问题解决。 菜鸟教程描述如下: 大部分的坑都是自己给自己造的~~~ 以下贴完整代码(我这个页面是以iframe被其他页面调用的,所以有个获取链接的操作以及拆分参数的方法) 请输入验证内容--> 确认4){//当type="number",属性maxlength不起作用 inNo=inNo.slice(0,4) document.getElementById("IdentifyNoCheckInput").value=inNo } varinNoArr=inNo.split(''); for(vari=0;i

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

[雪峰磁针石博客]pyspark工具机器学习(自然语言处理和推荐系统)1数据演进

在早期员工将数据输入系统,数据点非常有限,只占用少数几个字段。然后是互联网,每个人都可以轻松获取信息。现在,用户可输入并生成自己的数据。随着互联网用户数量呈指数级增长,用户创造的高数据增长率。例如:登录/注册表单允许用户填写自己的详细信息,在各种社交平台上上传照片和视频。这导致了巨大的数据生成以及快速处理数据量的且可扩展的框架的需求。 数据生成 设备都捕获数据,如汽车,建筑物,手机,手表,飞行引擎。 数据处理也从串行转向并行处理。 Spark Spark是处理海量数据集的框架,具有高速并行处理功能。它最初是加州大学伯克利分校AMPLabin 2009的研究项目,于2010年初开源。 2016年,Spark发布了针对深度学习的TensorFrames。 Spark底层使用RDD(弹性分布式数据集Resilient Distributed Dataset)的数据结构。它能够在执行过程中重新创建任何时间点。 RDD使用最后一个创建的RDD,并且总是能够在出现任何错误时进行重构。它们是不可变的,因为原始RDD还在。由于Spark基于分布式框架,因此它适用于master和worker节点设置。执行任何活动的代码首先写在Spark Driver上,数据实际驻留的workers之间共享。每个工作节点包含将实际执行代码的Executors。 Cluster Manager会检查下一个任务分配的各个工作节点的可用性。 Spark非常容易用于数据处理,机器学习和流媒体数据; 并且它相对非常快,因在内存中计算。由于Spark是通用的数据处理引擎,它可以很容易地与各种数据源一起使用,如HBase,Cassandra,Amazon S3,HDFS等.Spark为用户提供了四种语言选项:Java,Python,Scala和R. 参考资料 python测试开发项目实战-目录 python工具书籍下载-持续更新 python 3.7极速入门教程 - 目录 原文地址 本文涉及的python测试开发库 谢谢点赞! [本文相关海量书籍下载](https://github.com/china-testing/python-api-tesing/blob/master/books.md Spark Core Spark Core支持内存计算,可驱动并行分布式数据处理。 Spark Core负责管理任务,I/O操作,容错和内存管理等。 Spark组件 Spark SQL 主要处理结构化数据。获取有关数据结构的更多信息,以执行优化,是分布式SQL查询引擎。 Spark Streaming 以可扩展和容错的方式处理实时流数据。它使用微批处理来读取和处理传入的数据流。它创建微批流数据,执行批处理,并将其传递到文件存储或liveashboard。 Spark Streaming可以从多个来源(如Kafka和Flume)中获取数据。 Spark MLlib 以分布式方式在BigData上构建机器学习模型。使用Python的scikit学习库构建ML模型的传统技术在数据巨大时面临许多挑战,而MLlib可以提供大规模的特征工程和机器学习。 MLlib支持分类,回归,聚类,推荐系统和自然语言处理等算法。 Spark GraphX/Graphframe 在图形分析和图形并行执行方面表现优异。图形框架可用于理解底层关系并可视化数据。 参考:https://spark.apache.org/docs/latest/api/python/ 安装 参考:https://medium.com/@GalarnykMichael/install-spark-on-ubuntu-pyspark-231c45677de0

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

[雪峰磁针石博客]计算机视觉opcencv工具深度学习快速实战1人脸识别

使用OpenCV提供的预先训练的深度学习面部检测器模型,可快速,准确的进行人脸识别。 2017年8月OpenCV 3.3正式发布,带来了高改进的“深度神经网络”(dnn deep neural networks)模块。该模块支持许多深度学习框架,包括Caffe,TensorFlow和Torch / PyTorch。 基于Caffe的面部检测器在这里。 需要两组文件: 定义模型体系结构的.prototxt文件 .caffemodel文件,包含实际图层的权重 权重文件不包含在OpenCV示例目录。 OpenCV深度学习面部检测器如何工作? # 模型下载:https://itbooks.pipipan.com/fs/18113597-320346529 # 代码存放:https://github.com/china-testing/python-api-tesing/tree/master/opencv_crash_deep_learning # 技术支持qq群144081101(代码和模型存放) # USAGE # python detect_faces.py --image rooster.jpg --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel # import the necessary packages import numpy as np import argparse import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image") ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file") ap.add_argument("-m", "--model", required=True, help="path to Caffe pre-trained model") ap.add_argument("-c", "--confidence", type=float, default=0.5, help="minimum probability to filter weak detections") args = vars(ap.parse_args()) # load our serialized model from disk print("[INFO] loading model...") net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"]) # load the input image and construct an input blob for the image # by resizing to a fixed 300x300 pixels and then normalizing it image = cv2.imread(args["image"]) (h, w) = image.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) # pass the blob through the network and obtain the detections and # predictions print("[INFO] computing object detections...") net.setInput(blob) detections = net.forward() # loop over the detections for i in range(0, detections.shape[2]): # extract the confidence (i.e., probability) associated with the # prediction confidence = detections[0, 0, i, 2] # filter out weak detections by ensuring the `confidence` is # greater than the minimum confidence if confidence > args["confidence"]: # compute the (x, y)-coordinates of the bounding box for the # object box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") # draw the bounding box of the face along with the associated # probability text = "{:.2f}%".format(confidence * 100) y = startY - 10 if startY - 10 > 10 else startY + 10 cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2) cv2.putText(image, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2) # show the output image cv2.imshow("Output", image) cv2.waitKey(0) 执行: $ python detect_faces.py --image rooster.jpg --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel 上面的面部有74.30%的置信度。 尽管OpenCV的Haar级联因缺少“直接”角度的面孔,但通过使用OpenCV的深度学习面部探测器,依然能够测到脸部。 再来看三个面孔的示例: python detect_faces.py --image iron_chic.jpg --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel 视频,视频流和网络摄像头应用人脸检测 # USAGE # python detect_faces_video.py --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel # import the necessary packages from imutils.video import VideoStream import numpy as np import argparse import imutils import time import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file") ap.add_argument("-m", "--model", required=True, help="path to Caffe pre-trained model") ap.add_argument("-c", "--confidence", type=float, default=0.5, help="minimum probability to filter weak detections") args = vars(ap.parse_args()) # load our serialized model from disk print("[INFO] loading model...") net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"]) # initialize the video stream and allow the cammera sensor to warmup print("[INFO] starting video stream...") vs = VideoStream(src=0).start() time.sleep(2.0) # loop over the frames from the video stream while True: # grab the frame from the threaded video stream and resize it # to have a maximum width of 400 pixels frame = vs.read() frame = imutils.resize(frame, width=400) # grab the frame dimensions and convert it to a blob (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) # pass the blob through the network and obtain the detections and # predictions net.setInput(blob) detections = net.forward() # loop over the detections for i in range(0, detections.shape[2]): # extract the confidence (i.e., probability) associated with the # prediction confidence = detections[0, 0, i, 2] # filter out weak detections by ensuring the `confidence` is # greater than the minimum confidence if confidence < args["confidence"]: continue # compute the (x, y)-coordinates of the bounding box for the # object box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") # draw the bounding box of the face along with the associated # probability text = "{:.2f}%".format(confidence * 100) y = startY - 10 if startY - 10 > 10 else startY + 10 cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 0, 255), 2) cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2) # show the output frame cv2.imshow("Frame", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): break # do a bit of cleanup cv2.destroyAllWindows() vs.stop() 执行: python detect_faces_video.py --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel 参考资料 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 2018最佳人工智能机器学习工具书及下载(持续更新) 模型下载:https://itbooks.pipipan.com/fs/18113597-320346529 其他python人脸识别库介绍 python库介绍-face_recognition 人脸识别 可以命令识别人脸框。 $ face_detection --model cnn iron_chic.jpg iron_chic.jpg,79,422,243,258 iron_chic.jpg,146,272,310,108 iron_chic.jpg,194,144,330,7

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

[雪峰磁针石博客]python 3.7极速入门教程8语言比较与面试考试试题

筛选了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 暂时没找到文字的电子书

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

[雪峰磁针石博客]selenium自动化测试工具python笔试面试项目实战5键盘操作

说明 本文参考答案基于Chrome,分辨率1920*1080,在其他环境表现可能会不同。本文代码地址 参考书籍下载: Learning Selenium Testing Tools with Python-2014.pdf Selenium自动化测试 基于 Python 语言 - 2018.pdf 上机实操: 在新的TAB打开连接 打开:https://china-testing.github.io/ 选择"数据分析"栏目的文章 按住"Ctrl+TAB"选择"python"栏目的文章 切换到新的标签"python" 关闭新的标签"python" 关闭浏览器 参考答案 #!/usr/bin/python3 # -*- coding: utf-8 -*- # 讨论钉钉免费群21745728 qq群144081101 567351477 # CreateDate: 2018-10-17 import time from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get("https://china-testing.github.io/") driver.implicitly_wait(30) driver.maximize_window() element = driver.find_element_by_link_text('数据分析') element.click() time.sleep(3) element = driver.find_element_by_link_text('python') ActionChains(driver).key_down(Keys.CONTROL).click(element).key_up( Keys.CONTROL).perform() time.sleep(3) driver.switch_to.window(driver.window_handles[1]) time.sleep(3) driver.close() # 关闭当前TAB time.sleep(3) driver.quit() 面试问答 driver.quit() 和 driver.close()有什么区别? 2.selenium中按下和松开键如何表示? 3.简述ActionChains类的作用? 上机实操: 验证悬浮提示内容 打开:http://jqueryui.com/tooltip/ 鼠标移动到上图的"Your age:" 确认悬浮提示内容为'We ask for your age only for statistical purposes.' 关闭浏览器 参考答案 #!/usr/bin/python3 # -*- coding: utf-8 -*- # 讨论钉钉免费群21745728 qq群144081101 567351477 # CreateDate: 2018-10-17 import unittest import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.webdriver.common.action_chains import ActionChains class ToolTipTest (unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get("http://jqueryui.com/tooltip/") self.driver.implicitly_wait(30) self.driver.maximize_window() def test_tool_tip(self): driver = self.driver frame_elm = driver.find_element_by_class_name('demo-frame') driver.switch_to.frame(frame_elm) time.sleep(3) age_field = driver.find_element_by_id('age') ActionChains(self.driver).move_to_element(age_field).perform() time.sleep(3) tool_tip_elm = WebDriverWait(self.driver, 10).until( expected_conditions.visibility_of_element_located(( By.CLASS_NAME, 'ui-tooltip-content'))) # verify tooltip message self.assertEqual('We ask for your age only for statistical purposes.', tool_tip_elm.text) time.sleep(3) def tearDown(self): self.driver.close() if __name__ == '__main__': unittest.main(verbosity=2) 面试问答 1.move_to_element()有什么用途? 上机实操: 双击改变颜色 打开:http://api.jquery.com/dblclick/ 双击上图蓝色的框,把颜色该变成黄色 参考答案 #!/usr/bin/python3 # -*- coding: utf-8 -*- # 讨论钉钉免费群21745728 qq群144081101 567351477 # CreateDate: 2018-10-18 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import unittest class DoubleClickTest (unittest.TestCase): URL = 'http://api.jquery.com/dblclick/' def setUp(self): self.driver = webdriver.Chrome() self.driver.get(self.URL) self.driver.maximize_window() def test_double_click(self): driver = self.driver frame = driver.find_element_by_tag_name('iframe') driver.switch_to.frame(frame) box = driver.find_element_by_tag_name('div') # verify color is Blue self.assertEqual('rgba(0, 0, 255, 1)', box.value_of_css_property('background-color')) ActionChains(driver).move_to_element( driver.find_element_by_tag_name('body')).perform() ActionChains(driver).double_click(box).perform() # verify Color is Yellow self.assertEqual('rgba(255, 255, 0, 1)', box.value_of_css_property('background-color')) def tearDown(self): self.driver.close() if __name__ == '__main__': unittest.main(verbosity=2) 面试问答 1.double_click()有什么用途? 2.rgba的含义? 上机实操: 在新的TAB打开连接 打开:http://jqueryui.com/resources/demos/droppable/default.html 拖动左边的框到右边 参考答案 #!/usr/bin/python3 # -*- coding: utf-8 -*- # 讨论钉钉免费群21745728 qq群144081101 567351477 # CreateDate: 2018-10-18 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import unittest class DragAndDropTest (unittest.TestCase): URL = 'http://jqueryui.com/resources/demos/droppable/default.html' def setUp(self) : self.driver = webdriver.Chrome() self.driver.get(self.URL) self.driver.maximize_window() def test_drag_and_drop(self): driver = self.driver source = driver.find_element_by_id('draggable') target = driver.find_element_by_id('droppable') ActionChains(self.driver).drag_and_drop(source, target).perform() self.assertEqual('Dropped!', target.text) def tearDown(self): self.driver.close() if __name__ == '__main__': unittest.main(verbosity=2) 面试问答 1.drag_and_drop()有什么用途? 参考资料 讨论 钉钉群21745728 qq群144081101 567351477 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

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等操作系统。

用户登录
用户注册
修改密码
忘记密码