在Web页面中搜索浮动,然后使用这些浮动创建图形

时间:2015-05-01 13:10:38

标签: python

错误我正在尝试编写一个代码,该代码将扫描网页,查找所需数据,将其打包为浮动列表并使用这些浮动描绘图形。请考虑以下代码:

import matplotlib.pyplot as pyplot
from urllib.request import *
import re
import struct

x = []
temp = []
y = []

data = urlopen('http://www.banki.ru/products/currency/usd/').read()

temp = re.findall(b'<td>(\d\d,\d+)</td>', data) #searching for specific floats. Without 'b'' I get error.
del temp[-1]                                    #deleting the last element b/c it is invalid for my task

for num in range(0,len(y)):                     #data for Y-axis
    x.append(num)

for i in temp:                                  #Trying to 'unpack' byte-objects into dloats and then use them to create a graph
    num = struct.unpack('f',i)
    y.append(float(num[0]))

pyplot.plot(y,x)
pyplot.show()

我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/*/PycharmProjects/untitled/test.py", line 19, in <module>
    num = struct.unpack('f',i)
struct.error: unpack requires a bytes object of length 4

我理解错误。问题是,如何将带有字节对象的列表转换为浮点数?

--------------- --------------------- UPDATE 完成了这件事。

import matplotlib.pyplot as pyplot
from urllib.request import *
import re
import struct

x = []
temp = []
y = []

data = urlopen('http://www.banki.ru/products/currency/usd/').read()

temp = re.findall(b'<td>(\d\d,\d+)</td>', data)
del temp[-1]

for item in range(len(temp)):
    tm = temp[item].decode('utf8')
    tmn = tm.replace(',','.')
    y.append(float(tmn))

for num in range(0,len(y)):
    x.append(num)

pyplot.plot(x,y)
pyplot.show()

0 个答案:

没有答案