Beginning Python Chapter 21

# New
from urllib import request
from reportlab.graphics.shapes import *
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics import renderPDF
URL = 'http://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt'
COMMENT_CHARS = '#:'

drawing = Drawing(400, 200)
data = []
for line in request.urlopen(URL).readlines():
# New
    line = line.decode('utf-8')
    if not line.isspace() and not line[0] in COMMENT_CHARS:        
    data.append([float(n) for n in line.split()])

pred = [row[2] for row in data]
high = [row[3] for row in data]
low = [row[4] for row in data]
times = [row[0] + row[1]/12.0 for row in data]
lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width =300
# New
lp.data = [list(zip(times, pred)), list(zip(times, high)), list(zip(times, low))]
lp.lines[0].strokeColor = colors.blue
lp.lines[1].strokeColor = colors.red
lp.lines[2].strokeColor = colors.green

drawing.add(lp)
drawing.add(String(250, 150, 'Sunspots', fontSize = 14, fillColor = colors.red))

renderPDF.drawToFile(drawing, 'report2.pdf', 'Sunspots')


The above is the code of second project in <Beginning Python>. It is almost the same as the code was written in the book, but there are several difference there since I use the Python 3.4 to programme it.

1. In Python 3.4, module urllib only have the request module, not the urlopen module. And by using the request module, you could get the 2-bit result from the net, so if you need to process these data later, you need to decode it into string type first.

2. The data method in the LinePlot class cannot receive the tuple data, instead, it takes list data. And it is also the same for PloyLine class.

It is an easy project, the key element in this project is to learn how to use the reportlab module to convert the data into PDF graphs.

P.S. Reportlab can be easily downloaded from <https://pypi.python.org/pypi/reportlab/#downloads>. I downloaded the whl file and unzip it into the <lib> folder in the Python program files.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值