想把数据从网上填充到我桌面上的一个目录中,我能用一个ID而不是4个ID吗?

2024-06-16 09:54:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从wunderground.com获取数据,然后将其清理并保存到csv文件中。我有一个名为stations.csv的外部文件,其中包含4个站点的id,我需要获得每个站点12个月的所有数据,因此需要将48个文件保存到我的桌面数据库

以下是stations.csv:

KCASANFR131,37.778,-122.408

KDCWASHI48,38.913,-77.031

IBRITISH359,49.256,-123.245

KNYNEWYO639,40.755,-74.007

到目前为止,我能够从该网站获得数据,并将其保存到我桌面上一个名为“数据库”的目录中

以下是代码运行后数据库的外观:

database when first code runs

所以这看起来是对的,我只需要复制这四个站

下面是代码:

import urllib


def getData(month):

    url = "https://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KMDLAURE5&year=2017&month="+str(month)+"&graphspan=month&format=1"
    infile = urllib.urlopen(url)
    readLineByLine = infile.readlines()
    infile.close()

    return readLineByLine


for i in range(1,13):
    data = getData(i)
    filename = "database/0{}-2017.csv".format(i)
    outfile = open(filename,'w')
    row_count = len(data)

    for j in range(2, row_count):
        if(data[j] != '<br>\n' and data[j] != '\n'):
            outfile.write(data[j])
    outfile.close()

现在我正在尝试编辑原始代码,这样它就不会为1提供12个文件,而是为stations.csv中的4个站点ID中的每1个提供48个文件

下面是代码(现在已损坏):

import urllib

def getData(Id, month):

    url = "https://www.wunderground.com/weatherstation/WXDailyHistory.asp? ID=" + str(Id) + "&year=2017&month="+str(month)+"&graphspan=month&format=1"

    infile = urllib.urlopen(url)

    readLineByLine = infile.readlines()

    infile.close()

    return readLineByLine

f = open('stations.csv', 'r')


for elem in f.readlines():

    vals = elem.split(',')


    for i in range(1,13):

        data = getData(elem, i)

        filename = "database/{}-0{}-2017.csv".format(vals[0], i)

        outfile = open(filename,'w')

        row_count = len(data)

        for j in range(2, row_count):
            if(data[j] != '<br>\n' and data[j] != '\n'):
                outfile.write(data[j])
        outfile.close()

有了这个,它给出了正确的id和月份名称,但里面没有天气数据。下面是它的样子:

Picture of databse with edited code for 2017 data

我要做的最后一件事是编辑代码,以便它使用zfill(2),这样我就不会有看起来像011的月份,而是11个

请帮忙

谢谢


Tags: 文件csv代码informaturlfordata
1条回答
网友
1楼 · 发布于 2024-06-16 09:54:45

对于缺少数据的部分,请检查您正在访问的实际url。你可以先在浏览器里试试。在我看来,url中的空间是一个bug:

>>> import urllib
>>> len(urllib.urlopen("https://www.wunderground.com/weatherstation/WXDailyHistory.asp? ID=KCASANFR131&year=2017&month=1&graphspan=month&format=1").readlines())
2
>>> len(urllib.urlopen("https://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KCASANFR131&year=2017&month=1&graphspan=month&format=1").readlines())
62

至于格式化,您只需要在字符串中使用显式格式说明符。这应该可以做到:

filename = "database/{}-{02}-2017.csv".format(vals[0], i)

相关问题 更多 >