Python Wunderground原始输入d

2024-10-04 01:25:21 发布

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

我试图让程序要求用户的机场代码和年份(可以是任何-它不必是正确的或任何具体的)。我的教授只想让它询问然后打印数据。) 以下是我的代码:

import urllib2
from bs4 import BeautifulSoup

# Create / open a file called wunderdata.txt which will be a CSVfile
f = open('wunderdata.txt', 'w')

# Iterate through months and day
for m in range(1, 13):
    for d in range(1,32):
        # Check if already processed all days in the month
        if (m == 2 and d> 28):
            break
        elif (m in[4, 6, 9, 11] and d > 30):
            break

    # Open wunderground.com url
    airport = str(raw_input("Enter airport code: "))
    year = str(raw_input("Enter year: "))

    timestamp = '2009' + str(m) + str(d)
    print ("Getting data for ") + timestamp

    url = "http://www.wunderground.com/history/airport/" + airport + "/" + year + "/" + str(m) + "/" + str(d) + "/DailyHistory.html?"
    page = urllib2.urlopen(url)     

    # Get temperature from page
    soup = BeautifulSoup(page, "html.parser")


    #the following two lines are the original (textbook) and first attempt to fix
    # dayTemp = soup.body.wx-value.b.string
    dayTemp = soup.findAll(attrs={"class":"wx-value"})[6].get_text()
    seaLevel = soup.findAll(attrs={"class":"wx-value"})[16].get_text()      



    # Format month for timestamp
    if len(str(m)) < 2:
        mStamp = '0' + str(m)
    else:
        mStamp = str(m)

    # Format day for timestamp
    if len(str(d)) < 2:
        dStamp = '0' + str(d)
    else:
        dStamp = str(d)

    # Build timestamp
    #timestamp = '2009' + mStamp + dStamp

    # Write timestamp and temperature to file
    f.write(timestamp + ',' + dayTemp + " " + "Sea Level Pressure: " + seaLevel + '\n')

# Done getting data! Close file.
f.close()

不管怎样,输入时会出现以下情况:

python get-weather-data.py
Enter airport code: KBUF
Enter year: 2009
Getting data for 200911
Enter airport code: KBUF
Enter year: 2009
Getting data for 200912
Enter airport code: KBUF
Enter year: 2009
Getting data for 200913

我希望是这样

python get-weather-data.py
Enter airport code: KBUF
Enter year: 2009
Getting data for 200911
Getting data for 200912
Getting data for 200913

快来人救命!我是一个初学者,所以我对python了解不多,但非常感谢您的帮助:)


Tags: andinfordatagetifcodeyear
2条回答

问题是,您要求在循环中输入。所以,每次它通过代码时,你都要求输入。你知道吗

如果只想获取一次输入,请将其置于循环之外。考虑:

airport = str(raw_input("Enter airport code: "))
year = str(raw_input("Enter year: "))

for m in range(1, 13):
    for d in range(1,32):
        # Check if already processed all days in the month
...

你的问题标题有点误导,因为一般用户不知道“wunderdata”是什么。你的问题也与此无关。你知道吗

从我对你的问题的理解来看,这就像把你的raw_input语句放在for循环之外一样简单:

# Create / open a file called wunderdata.txt which will be a CSVfile
f = open('wunderdata.txt', 'w')

# Enter necessary data
airport = str(raw_input("Enter airport code: "))
year = str(raw_input("Enter year: "))

# Iterate through months and day
for m in range(1, 13):
    ...

我相信raw_input已经返回了一个字符串,因此不需要进行转换,但是,由于我使用的是python3.x,所以我不能完全确定这一点

相关问题 更多 >