赞
踩
《python基础教程》画幅好画使用reportlab模块画出太阳黑子的曲线图。
源代码:
from reportlab.lib import colors
from urllib import urlopen
from reportlab.graphics.shapes import *
from reportlab.graphics.charts.lineplots import LinePlot
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 urlopen(URL).readlines():
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
lp.data = [zip(times,pred),zip(times,high),zip(times,low)]
drawing.add(lp)
renderPDF.drawToFile(drawing,'report.pdf','Sunspots')
但是这个是基于python2, 但是很多开始使用python3。用python3运行这段代码的时会报 typeerror
TypeError: 'zip' object is not subscriptable
这是因为在python2 中zip函数返回的是list,python3 中zip函数返回的是迭代器。所以会出现上面的错误。
python3 的源代码:
from reportlab.lib import colors from reportlab.graphics.shapes import * from reportlab.graphics import renderPDF from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.charts.textlabels import Label import re file = open('Predict.txt','r') drawing = Drawing(400,200) data = [] for line in file.readlines(): lineList = [] if re.match('#',line): continue line = re.sub('\s+','%',line) lineList = line.split('%') data.append(lineList) pred = [float(row[2]) for row in data] high = [float(row[3]) for row in data] low = [float(row[4]) for row in data] time = [ float(row[0]) + float(row[1])/12.0 for row in data] lp = LinePlot() lp.x= 50 lp.y= 50 lp.height = 125 lp.width = 300 #通过list函数将zip的返回转化成list lp.data = [list(zip(time,pred)),list(zip(time,high)),list(zip(time,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, 'report.pdf','Sunspots')
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。