从网站上的 Table 中提取数字

Extracting Numbers From a Table on a Website

我正在尝试从网站提取数据供个人使用。我只想要整点的降水。我快完成了,但我无法总结数据。我认为是因为它返回空值,and/or 因为数据不全是整数?也许使用 for 循环不正确?

代码如下:

import urllib2
from bs4 import BeautifulSoup
import re

url = 'http://www.saiawos2.com/K61/15MinuteReport.php'
page = urllib2.urlopen(url) 
soup  = BeautifulSoup(page.read())

table = soup.findAll('table')[0]
rows = table.findAll('tr')

second_columns = []
thirteen_columns = []

for row in rows[1:]:
    second_columns.append(row.findAll('td')[1]) #Column with times
    thirteen_columns.append(row.findAll('td')[12]) #Precipitation Column

for second, thirteen in zip(second_columns, thirteen_columns):
    times = ['12:00','11:00','10:00','09:00','08:00','07:00','06:00',
         '05:00','04:00','03:00','02:00','01:00','00:00','23:00',
         '22:00','21:00','20:00','19:00','18:00','17:00','16:00',
         '15:00','14:00','13:00',]
    time = '|'.join(times) 
    if re.search(time, second.text):
        pcpn = re.sub('[^0-9]', '', thirteen.text) #Get rid of text
        print sum(pcpn[1:]) #Print sum and get rid of leading zero

也许有一种简单的方法可以做到这一点,但这是我目前所拥有的。当我 sum(pcpn) 时,它为带有打印语句的行给出以下错误:

TypeError: unsupported operand type(s) for +: 'int' and 'unicode'

问题是 sum 试图找到整数列表的总和,因为您传递了一个它无法求和的 unicode 字符列表。

您需要做的就是将列表的每个元素映射到int并将其传递给sum。

if re.search(time, second.text):
        pcpn = re.findall(r'[0-9.]+', thirteen.text) 
        print sum( float(x) for x in pcpn )

它有什么作用?

  • re.findall(r'[0-9.]+', thirteen.text) 而不是使用 re.sub 函数,我们使用 re.findall() 它将为您提供匹配列表,然后可以将其传递给 sum() 函数。这里匹配的是数字。

  • sum( float(x) for x in pcpn ) 将每个元素映射到 float 并求和。

    • ( float(x) for x in pcpn ) 是一个 generator 语句,它在移动中创建元素。