Python3实践项目一:生成0-5岁宝宝生长发育报告

face.jpg

​本文介绍基于Python3.5.2,根据世界卫生组织发布的0-5岁宝宝生长发育标准百分位数曲线数据,以及宝宝的身长\高,体重,头围监测数据,绘制宝宝的身长\高,体重,头围,体重指数,身长\身高别体重的曲线图,然后生成.docx格式的文档,最后将文档转变为PDF格式的报告。

image

  • 一、获取数据

在https://www.who.int/childgrowth/standards/zh/找到需要的数据列表,然后利用爬虫获取相应的数据,并将数据以.xls格式存储,最后再读取形成字典形式。

1,用到的库

bs4:版本4.6.0
pandas:版本0.23.4
numpy:版本1.16.4
urllib:Python3.5.2内置版

2,主要知识点

  • 打开网页
from urllib import request
from bs4 import BeautifulSoup as bs
html = request.urlopen(all_url) # all_url网页地址,打开网页
bs_data = bs(html.read(), "html5lib")  # 解析网页
  • 数据存储与读取
import pandas as pd
# 将numpy的array格式的数据变为pandas的DataFrame格式
pd_data = pd.DataFrame(np.array(data_list), columns=df_column)
# 直接写入excel中
pd_data.to_excel(excel_path, sheet_name=name, encoding='gb2312', index=False)
# 读取数据
read_data = pd.read_excel(excel_path, sheet_name=name, header=1)

image

  • 二、绘图

首先利用matplotlib绘制标准曲线图,然后将监测数据经过三次样条插值,再绘制宝宝的生长曲线图。

1,用到的库

matplotlib:版本3.0.2
scipy:版本1.2.0

2,主要知识点

  • 显示中文与负号
from pylab import mpl # 作图显示中文
mpl.rcParams['font.sans-serif'] = ['STZhongsong']  # 设置中文字体为新宋体
mpl.rcParams['axes.unicode_minus'] = False # 显示负号
  • 设置边框颜色与宽度
ax = plt.gca()  # 获取边框
ax.spines['top'].set_color(self.color)
ax.spines['right'].set_color(self.color)
ax.spines['left'].set_color(self.color)
ax.spines['bottom'].set_color(self.color)
ax.spines['bottom'].set_linewidth(1.2)
ax.spines['left'].set_linewidth(1.2)
ax.spines['top'].set_linewidth(1.2)
ax.spines['right'].set_linewidth(1.2)
  • 设置主、次网格线的刻度、粗度、颜色
from matplotlib.ticker import MultipleLocator
ax.yaxis.set_minor_locator(MultipleLocator(0.5)) # 设置y轴次刻度
ax.xaxis.set_minor_locator(MultipleLocator(1))  # 设置x轴次刻度
ax.xaxis.grid(True, which='major', linewidth=1.2, color=color)  # 使用主刻度绘制x坐标轴的网格
ax.yaxis.grid(True, which='minor', linewidth=0.7, color=color)  # 使用次刻度绘制y坐标轴的网格
ax.xaxis.grid(True, which='minor', linewidth=0.7, color=color)  # 使用次刻度绘制x坐标轴的网格
ax.yaxis.grid(True, which='major', linewidth=1.2, color=color)  # 使用主刻度绘制y坐标轴的网格
  • 设置网格线在绘制线的下方
ax.set_axisbelow(True)
  • 设置x轴标签在图片上方的轴
ax.xaxis.tick_top()
  • 设置标签线的长度、颜色、粗度
from pylab import tick_params, minorticks_on 
minorticks_on()
tick_params(axis='y', which='major', width=1, length=4, colors=color)
tick_params(axis='x', which='major', width=1, length=2, colors=color)
tick_params(which='minor', length=0)
  • 设置图中图
ax2 = fig.add_axes([left, bottom, width, height])  # 图中图
  • 绘制表格

table = ax2.table(cellText=cellText, colLabels=colLabels, loc='lower center', cellLoc='left',
                  colWidths=list(table_w))
table.auto_set_font_size(False)  # 取消自动设置字体大小
table.set_fontsize(8) # 表格字体大小设置
table_props = table.properties()
table_cells = table_props['child_artists']
for cell in table_cells:
    cell._text.set_color(self.color)  # 设置字体颜色
    cell.set_edgecolor(self.color)   # 设置表格线的颜色
  • 保存图片去掉多余空白
fig = plt.gcf()
fig.savefig(fig_path, dpi=100, bbox_inches='tight') 
  • 三次样条插值
from scipy import interpolate
# 三次样条插值插值
t = interpolate.splrep(x_data, y_data, k=3)
day_data = np.linspace(min(x_data), max(x_data), num=1000)
interp_data = interpolate.splev(day_data, t)

image

  • 三、生成.docx文件

将生成的图片以及宝宝的信息整合到.docx文档中。

1,用到的库

docx:版本0.8.10

2,主要知识点

  • 字体、颜色、大小、位置设置
from docx import Document
from docx.shared import Inches, RGBColor
from docx.oxml.ns import qn
from docx.shared import Pt
import docx.enum.text as s
# 新建Word文档
document = Document()

p = document.add_paragraph('')
text1 = p.add_run(str_para) # 添加内容
text1.font.size = Pt(24)                                # 字体大小
text1.bold = True                                       # 字体是否加粗
text1.font.name = 'Times New Roman'                     # 控制是西文时的字体
text1.element.rPr.rFonts.set(qn('w:eastAsia'), '华文中宋')  # 字体设置
p.paragraph_format.alignment = s.WD_ALIGN_PARAGRAPH.CENTER  # 位置设置
text1.font.color.rgb = RGBColor(*color)  # 颜设置
  • 图片居中
document.add_paragraph('')
tab = document.add_table(rows=1, cols=3)  # 添加一个1行3列的空表
cell = tab.cell(0, 1)  # 获取某单元格对象(从0开始索引)
ph = cell.paragraphs[0]
run = ph.add_run()
run.add_picture(ig_path, width=Inches(5))
  • 页边距设置

se = add_docu.add_section()
se.left_margin = Inches(0.4)  # 左边距离
se.right_margin = Inches(0.4)  # 右边距离
  • 表格设置

table = document.add_table(rows=5, cols=2, style=style)  # 添加表格5行、2列
# 添加第二行的内容
hdr_cells = table.rows[1].cells
hdr_cells[0].text = '宝宝昵称'
hdr_cells[1].text = b.b_n

# 设置表格内文字的大小、颜色,表格线的颜色
for row in table.rows:
    for cell in row.cells:
        paragraphs = cell.paragraphs
        for paragraph in paragraphs:
            for run in paragraph.runs:
                font = run.font
                font.size = Pt(15)
                font.color.rgb = RGBColor(*color)

四、转化为PDF格式

将.docx文档转化为PDF格式时,如果程序的错误信息显示下面的内容:

C:\\Program Files (x86)\\Microsoft Office\\Office12\\2052\\WDMAIN11.CHM'

这说明是word输出pdf出现错误,需要下载插件SaveAsPDFandXPS.exe,安装即可。

1,用到的库

win32com

2,主要知识点

  • .docx转为PDF
from win32com import client
word = client.DispatchEx("Word.Application")
worddoc = word.Documents.Open(doc_path, ReadOnly=1)
worddoc.SaveAs(pdf_path, FileFormat=17)
worddoc.Close()

image

五、报告示例:男宝

image

image

image

image

image

image

image

image

image

image

image

image

image

点击获得项目源码。欢迎Follow,感谢Star!!! 扫描关注微信公众号pythonfan,获取更多。

image

image

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AnFany

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值