# 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.