【发布时间】:2015-11-07 03:54:56
【问题描述】:
我正在尝试学习 Python 并且正在研究https://automatetheboringstuff.com/chapter14/ 上的一些示例——这个是提取简单的天气数据。运行脚本时出现错误,我似乎无法找到...主要的答案,因为我不知道如何询问它,所以这里是:
我的代码(来自书中)
#! python3
# quickWeather.py - Prints the weather for a location from the command line
import json
import requests
import sys
# Compute location from command line arguments.
if len(sys.argv) < 1:
print('Usage: quickweather.py location')
sys.exit()
location = ' '.join(sys.argv[1:])
# Todo: Download the json data from OpenWeatherMap.org's API
url = 'http://api.openweathermap.org/data/2.5/forecast/city?id=5391811&APPID=5103aa7d5415db6xxxxxxxxxxxxxxx' % (location)
response = requests.get(url)
response.raise_for_status()
# Load JSON data into Python variable.
weatherData = json.loads(response.text)
w = weatherData['list']
print('Current weather in %s:' % (location))
print(w[0]['weather'][0]['main'], '-', w[0]['weather'][0]['description'])
print()
print('Tomorrow:')
print(w[1]['weather'][0]['main'], '-', w[1]['weather'][0]['description'])
print()
print('Day after tomorrow:')
print(w[2]['weather'][0]['main'], '-', w[2]['weather'][0]['description'])
我的控制台错误
rooster@python_tests $ python3 quickWeather.py
Traceback (most recent call last):
File "quickWeather.py", line 16, in <module>
url = 'http://api.openweathermap.org/data/2.5/forecast/city?id=5391811&APPID=5103aa7d5415db6xxxxxxxxxxxxxxxx' %(location)
TypeError: not all arguments converted during string formatting
如果我从 url 路径中删除 %(位置),控制台将打印除位置之外的数据,在本例中为圣地亚哥。
我知道这是一个微不足道的问题,如果我对 Python 有更多的了解,那将很容易回答,但现在,经过 2 个小时的研究,我很想知道到底发生了什么。
感谢您的帮助。
【问题讨论】:
-
那么应该在字符串的哪个位置插入位置?您缺少
%s占位符。 -
%字符串格式化的工作方式是,您必须在字符串中为元组中的每个值添加一个%x占位符。 -
% 在第一个打印语句中......这本书有点偏离(对于初学者),因为它甚至没有提到需要 API 密钥,但这是我的完整字符串APIKEY(我可以稍后重置)-(位置)应该获取城市名称...只需将其粘贴到浏览器中即可api.openweathermap.org/data/2.5/forecast/…
标签: python