[英]weather checking with sys.argv
我正在嘗試使用sys.argv
制作天氣搜索工具,只是想要一些幫助。 我有當前的代碼
問題是當我使用命令行搜索時,我需要輸入國家/地區。 有沒有辦法只搜索城市?:
#! /usr/bin/env python3
import webbrowser
import sys
import pyperclip
import re
if len(sys.argv) > 1:
#Get address from command line.
address = ' '.join(sys.argv[1:])
else:
address = pyperclip.paste()
webbrowser.open('https://www.timeanddate.com/weather/' + address)
命令行:
./weather.py spain/madrid
./weather.py uk/london
pip install geocoder
import geocoder
g = geocoder.geonames('madrid', key='YOURUSERNAMEHERE')
...
webbrowser.open('https://www.timeanddate.com/weather/' + g.country + address)
正如@Kalma 提到的, g.country
返回'United Kingdom'
而不是'UK'
。 您可能需要將這些值映射到 timeanddate.com 接受的值。
如前所述,可能有許多軟件包可以解決問題,並且可能沒有一個適用於某些城市名稱。 但是, geonamescache 非常易於使用,並且可以為唯一名稱提供技巧。 這是一個示例(將返回“加拿大”作為“多倫多”作為輸入)
pip install geonamescache
import geonamescache as gnc
gc = gnc.GeonamesCache()
query = 'Toronto'
citykey = list(gc.get_cities_by_name(query)[0])[0]
ccode = gc.get_cities_by_name(query)[0][citykey]['countrycode']
countries = gc.get_countries()
country_name = countries[ccode]['name']
print(country_name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.