python - 开放的天气图 API 没有通过 python 请求提供正确的数据
问题描述
所以,我正在用python中的语音识别制作一个语音助手。我正在使用开放天气地图 API。在我的 python 程序中调用 API 时返回错误的结果。
当我在网络上使用带有给定 api 密钥的链接时,该 API 可以完美运行并返回正确的结果,但是当我在我的 python 程序中使用它时,它会在孟买、德里、加尔各答等一些城市返回错误的结果,但当我问它时,结果是正确的纽约的天气。这很奇怪!
查询是我命令的语句 - “纽约的天气怎么样”
elif "weather" in query:
query = query.strip(" weather in ")
query = query.replace(" ", "")
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=xxxxx&units=metric'.format(query)
res = requests.get(url)
data = res.json()
temp = data['main']['temp']
wind_speed = data['wind']['speed']
description = data['weather'][0]['description']
print(str(description) + " with a temperature of " + str(temp) + "°C and a wind speed of " + str(wind_speed) + " km/hr")
speak(str(description) + " with a temperature of " + str(temp) + "°C and a wind speed of " + str(wind_speed) + " kilometer per hour")
解决方案
首先,strip
不能那样工作。Strip 从字面上删除由这些字符组成的任何前缀和后缀。它不会切割或移除给定的部分。
在你的情况下:
>>> print("what is the weather in new york".strip(" weather in "))
s the weather in new york
另一个例子:
>>> print("aaaaaaaaabsomethinghereaa".strip("a"))
bsomethinghere
>>> print("aaaaaaaaabsomethinghereaa".strip("ab"))
somethinghere
>>> print("1234567aabsomethinghereaa".strip("ab7654321"))
somethinghere
如您所见,顺序无关紧要,这些字符的任何组合都会从开头和结尾删除。
这给了我们第二步:调试。
如果某些事情没有按预期工作,请检查您是否正确。如果您使用此处的文本,请打印文本操作的每个步骤。您仅将脚本结果与手动结果进行了比较,而没有检查导致这些结果的每个步骤。
如何修复这部分?
你必须剪断你的绳子,只留下城市。这意味着你必须找到“天气”的结局,然后把一切都拿走。
要查找子字符串的开头,您可以使用find
. 如果要结束,请添加文本的长度。
>>> query = "what is the weather in new york"
>>> query = query[query.find("weather in")+10:]
>>> query = query.replace(" ", "")
>>> print(query)
newyork
推荐阅读
- c++ - 如何正确初始化此指针以避免分段错误?
- javascript - 如何在 .val() jquery 函数中添加多个变量
- node.js - 在'"db": "json-server -w db.json -p 3001"'中,这里的'-w'是什么意思?
- power-automate - 带有提醒的定期电子邮件
- javascript - 使用 res.render("url", {object}) url 不会改变,但视图会改变
- php - codeigniter如何根据动态值连接第二个数据库
- r - 在R中拆分数据集,以便将所有具有相同名称的列分成两个相等的部分?
- c# - C# 重载在类中找到的对象的属性
- android - 是否可以在静态方法中使用视图绑定?
- javascript - 用 css 在三个点后添加显示更多文本