我正在尝试使用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)
command line:
./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)
如前所述,可能有许多软件包可以解决这个问题,并且可能都不适合某些城市名称。但是,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)