簡體   English   中英

使用 sys.argv 檢查天氣

[英]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

1-) 注冊 geonames 以使用 API

  • 創建一個新的用戶帳戶https://www.geonames.org/login
  • 從郵件激活您的帳戶
  • 在點擊激活鏈接后的重定向頁面上,激活網絡服務

2-) 安裝地理編碼器

pip install geocoder

3-) 使用 API

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM