<jupyter_start><jupyter_text>Part 1.  Get the Weather Description and Amount of Precipitation for Each City<jupyter_code># 1. Dependacies

import numpy as np
import random
import requests
import pandas as pd
from citipy import citipy
import matplotlib.pyplot as plt
import os
import gmaps
from config import g_key
from config import weather_api_key
from datetime import datetime

# Reloading the config since adding new keys

import importlib
import config

importlib.reload(config)

from config import challenge_weather_key

from config import g_key2
# 2. Generating new list of random coordinaties
lats = np.random.uniform(-90.00, 90.00, size=1500)
long = np.random.uniform(-180.00, 180.00, size=1500)
uni_coords = zip(lats, long)
uni_coords

coordinates = list(uni_coords)

coordinates
# 3. Finding unique cities closest to the 1500 coordinates, removing duplicates

cities= []

for coords in coordinates:
    city = citipy.nearest_city(coords[0], coords[1]).city_name
    
    # if city is unique, then it is added, as to remove duplicates
    if city not in cities:
        cities.append(city)
        
print(len(cities))

cities
#  4. Performing an API call with OpenWeatherMap

url = f"http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID={weather_api_key}"

city_data = []


# 5. Retriveing information from the OpenWeatherMap API

# Printing begining of logging

print("Beginning Data Retreival           ")
print("------------------------------------")

record_count = 1

set_count = 1

for w, city in enumerate(cities):
    print(w, city)
    
    if (w % 50 == 0 and w >= 50):
        set_count += 1
        record_count = 1

    city_url = f"{url}&q={city.replace(' ','+')}"
    
    print(f"Processing Record {record_count} of Set {set_count} | {city}")
    
    record_count += 1
    
    try:
        # Parse the JSON and retrieve data, assign a variable first
        
        city_weather = requests.get(city_url).json()
        
        city_lat = city_weather["coord"]["lat"]
        
        city_lng = city_weather["coord"]["lon"]
        
        city_max_temp = city_weather["main"]["temp_max"]
        
        city_humidity = city_weather["main"]["humidity"]
        
        city_clouds = city_weather["clouds"]["all"]
        
        city_wind = city_weather["wind"]["speed"]
        
        city_country = city_weather["sys"]["country"]
        
        city_desc = city_weather["weather"][0]["description"]
        
        try:
            
            city_rain = city_weather["rain"]["1h"]
            
        except (KeyError):
            
            city_rain = 0
            
        try:
            
            city_snow = city_weather["snow"]["1h"]
            
        except (KeyError):
            
            city_snow = 0

        city_data.append({"City": city.title(),
                          "Country": city_country,
                          "Lat": city_lat,
                          "Lng": city_lng,
                          "Max Temp (F)": city_max_temp,
                          "% Humidity": city_humidity,
                          "% Cloudiness": city_clouds,
                          "Wind Speed (mph)": city_wind,
                          "Current Description": city_desc,
                          "Rain (inches)": city_rain,
                          "Snow (inches)":city_snow
                         })

# If an error is experienced, skip the city.

    except:
        
        print("City not found. Skipping...")

#       Countinues the loop without stopping
        pass

# Indicate that Data Loading is complete.
print("-----------------------------")
print("Data Retrieval Complete      ")
print("-----------------------------")
        
len(city_data)
# 6. Converting to a dataframe
city_data_new_df = pd.DataFrame(city_data)

city_data_new_df.head(10)
# 7. Saving the dataframe as a csv file in the "challenge_data" folder

convert_df2csv = "challenge_data/WeatherPy_database.csv"

city_data_new_df.to_csv(convert_df2csv, index_label = "City_ID")

city_data_new_df = pd.read_csv("challenge_data/WeatherPy_database.csv")

city_data_new_df.head(10)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11838006230529595, 'fraction_numerical': 0.015336688233884496, 'mean_word_length': 2.1149253731343283, 'pattern_counts': {'":': 11, '<': 5, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '352615', 'license': 'MIT', 'n_tokens_mistral': 1325, 'n_tokens_neox': 1258, 'n_words': 320, 'path': 'jupyter_notebooks/Weather_Database.ipynb', 'repo_name': 'SiMewL8/World_Weather_Analysis', 'size': '4173'}