想要在现有的python代码中运行循环

时间:2019-10-02 12:58:46

标签: python api

我正在运行一个python程序,以使用API​​从DarkSky天气网站获取天气数据。 截至目前,我通过一次获取纬度和经度来一次获取一个位置的数据。

我想要的是...我想一次给出2-4个位置,我的代码应该获取我在代码中提到的所有Location(latitude, longitude)的数据

import os
import warnings
import requests
import pandas as pd
import numpy as np
from darksky import forecast
from datetime import datetime
from tqdm import tqdm

def ping_darksky(time, key):

    WeatherData = forecast(key, *Location, time=day.isoformat())

    fetch = {
        'day': time,
        'windSpeed': WeatherData["daily"]["data"][0].get('windSpeed', np.nan),
        'windGust': WeatherData["daily"]["data"][0].get('windGust', np.nan),
        'windBearing': WeatherData["daily"]["data"][0].get('windBearing', np.nan)}
    return fetch

def switch_key():


    with open("secret_key.txt", 'r') as key_file:
        api_keys = key_file.read().splitlines()

    for api_key in api_keys:
        yield api_key

#38.9072, 77.0369(DC)
#40.3029, 74.7337(Mercer)
#39.1547, 77.2405(Montgomery)
#40.1461, 82.4753(Licking)

# Define location(Lat & Long).
Location = (40.1461, -82.4753)
# Set up dataframe and path to which it will be saved.
COLUMNS = ["day", "windSpeed", "windGust"]
WEATHER_Location = pd.DataFrame(columns=COLUMNS)
DATAOUT = os.path.join("data", "weather_WeatherData_daily.csv")
# Define start variables for the loop.

##YYYY, MM,DD
START = datetime(2018,1,27)
KEYGEN = switch_key()
KEY = next(KEYGEN)


if __name__ == "__main__":
    print("Start data collection.")
    for day in tqdm(pd.date_range(START, periods=190)):
        try:
            row = ping_darksky(key=KEY, time=day)
            WEATHER_Location = WEATHER_Location.append(row, ignore_index=True)
        # If the server refuses to connect, change the key.
        except requests.exceptions.HTTPError:
            try:
                KEY = next(KEYGEN)
                row = ping_darksky(key=KEY, time=day)
                WEATHER_Location = WEATHER_Location.append(row, ignore_index=True)
                continue
        # If there are no keys left, break the loop prematurely.
            except StopIteration:
                warnings.warn(
                    "End of keys reached. Your dataset might be incomplete.")
                break
        # Save data in each iteration.
        # This way you should end up with something at least.
        finally:
            WEATHER_Location.to_csv(DATAOUT)

    print("Wrote {} rows".format(WEATHER_Location.shape[0]))

2 个答案:

答案 0 :(得分:0)

您可以:

  1. 创建位置列表
  2. 创建字典

并通过使用其中的值来调用相关函数。 使用清单:

#locations = [[40.1461, -82.4753],[123, 213],........]
locations = [[40.1461, -82.4753],[123, 213]]

def ping_darksky(time, key):

    for location in locations:
      WeatherData = forecast(key, location, time=day.isoformat())
      fetch = {
        'day': time,
        'windSpeed': WeatherData["daily"]["data"][0].get('windSpeed', np.nan),
        'windGust': WeatherData["daily"]["data"][0].get('windGust', np.nan),
        'windBearing': WeatherData["daily"]["data"][0].get('windBearing', np.nan

        #here add up the data and finally return
        print(fetch)

使用字典:

locations = {40.1461: -82.4753, 123: 213}
for key,value in dicta.items():
      WeatherData = forecast(key, *[key, value], time=day.isoformat())

但是,如果预测功能需要列表,则最好选择列表。

答案 1 :(得分:0)

我会将位置存储在元组的字典(又称为哈希图)中,并在键上循环

locations = {"DC":(38.9072, 77.0369), "Mercer":(40.3029, 74.7337), "Montgomery":(39.1547, 77.2405), "Licking":(40.1461, 82.4753)}
for key in locations.keys():
       location = locations[key]
       <YOUR MAIN CODE>

我会使用字典,以便将来如果需要,可以通过名称选择位置