我正在尝试让程序向用户询问机场代码和年份(可以是任何东西-它不必是正确的或任何特定的东西。我的教授只是想让它询问,然后打印数据。)下面是我的代码:
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了解不多,但非常感谢帮助:)
发布于 2016-10-26 23:48:09
问题是您在循环中请求输入。因此,每次它通过该代码时,您都会请求输入。
如果你只想得到一次输入,那就把它放在循环之外。考虑一下:
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
...发布于 2016-10-26 23:56:31
你的问题标题有点误导,因为普通用户不知道"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
https://stackoverflow.com/questions/40266294
复制相似问题