Python Wunderground raw_input数据

时间:2016-10-26 15:27:22

标签: python loops input raw-input

我正在尝试让程序向用户询问机场代码和年份(可以是任何东西 - 它不一定是正确的或任何特定的。我的教授只是想让它询问然后打印数据。 ) 这是我的代码:

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知之甚少,但非常感谢帮助:)

2 个答案:

答案 0 :(得分:0)

问题是您要求在循环中输入。因此,每次通过该代码时,您都会要求输入。

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

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
...

答案 1 :(得分:0)

您的问题标题有点误导,因为普通用户不知道“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已经返回一个字符串,因此转换不是必需的,但是,由于我使用的是python 3.x,所以我并不完全确定。