How to know if a request is fulfilled on python? - python

I making a request to download some data on python from Copernicus website. The thing is that I want to know when the request is fulfilled and when the download is finished.
Is is solid enough to work with 2 flags(request_finished and download_finished)?
import cdsapi
c = cdsapi.Client()
latitude = 43.1 # North, South
longitude = -1.5 # West , East
#str(latitude)+'/'+str(longitude)+'/'+str(latitude)+'/'+str(longitude)
r = c.retrieve(
'reanalysis-era5-single-levels',
{
'product_type':'reanalysis',
'variable':[
'100m_u_component_of_wind','100m_v_component_of_wind','10m_u_component_of_wind','10m_v_component_of_wind','2m_temperature',
'surface_pressure'
],
'area' : str(latitude)+'/'+str(longitude)+'/'+str(latitude)+'/'+str(longitude), # North, West, South, East. Default: global
'year':'2018',
'grid':'0.1/0.1', # Latitude/longitude grid in degrees: east-west (longitude) and north-south resolution (latitude). Default: reduced Gaussian grid
'month':'01',
'day':[
'01','02','03',
'04','05','06',
'07','08','09',
'10','11','12',
'13','14','15',
'16','17','18',
'19','20','21',
'22','23','24',
'25','26','27',
'28','29','30',
'31'
],
'time':[
'00:00','01:00','02:00',
'03:00','04:00','05:00',
'06:00','07:00','08:00',
'09:00','10:00','11:00',
'12:00','13:00','14:00',
'15:00','16:00','17:00',
'18:00','19:00','20:00',
'21:00','22:00','23:00'
],
'format':'netcdf'
}
)
request_finished = 1
r.download('download_grid_reduction_one_month_point_limit.nc')
download_finished = 1

Related

How to add Search plugin in folium for multiple fields?

I'm trying to add a search bar in folium map using folium plugins.
Data:
import geopandas
states = geopandas.read_file(
"https://raw.githubusercontent.com/PublicaMundi/MappingAPI/master/data/geojson/us-states.json",
driver="GeoJSON",
)
states_sorted = states.sort_values(by="density", ascending=False)
states_sorted.head(5).append(states_sorted.tail(5))[["name", "density"]]
def rd2(x):
return round(x, 2)
minimum, maximum = states["density"].quantile([0.05, 0.95]).apply(rd2)
mean = round(states["density"].mean(), 2)
import branca
colormap = branca.colormap.LinearColormap(
colors=["#f2f0f7", "#cbc9e2", "#9e9ac8", "#756bb1", "#54278f"],
index=states["density"].quantile([0.2, 0.4, 0.6, 0.8]),
vmin=minimum,
vmax=maximum,
)
colormap.caption = "Population Density in the United States"
id name density geometry
0 01 Alabama 94.650 POLYGON ((-87.35930 35.00118, -85.60667 34.984...
1 02 Alaska 1.264 MULTIPOLYGON (((-131.60202 55.11798, -131.5691...
2 04 Arizona 57.050 POLYGON ((-109.04250 37.00026, -109.04798 31.3...
3 05 Arkansas 56.430 POLYGON ((-94.47384 36.50186, -90.15254 36.496...
4 06 California 241.700 POLYGON ((-123.23326 42.00619, -122.37885 42.0...
Folium Map:
import folium
from folium.plugins import Search
m = folium.Map(location=[38, -97], zoom_start=4)
def style_function(x):
return {
"fillColor": colormap(x["properties"]["density"]),
"color": "black",
"weight": 2,
"fillOpacity": 0.5,
}
stategeo = folium.GeoJson(
states,
name="US States",
style_function=style_function,
tooltip=folium.GeoJsonTooltip(
fields=["name", "density"], aliases=["State", "Density"], localize=True
),
).add_to(m)
statesearch = Search(
layer=stategeo,
geom_type="Polygon",
placeholder="Search for a US State",
collapsed=False,
search_label="name",
weight=3,
).add_to(m)
folium.LayerControl().add_to(m)
colormap.add_to(m)
m
In the above map user can search only by US state name, is it possible to include multiple fields for search, like searching based on density/ id / Name??

adjacency matrix map manipulation

0
I'm making a simple text based adventure game. My code uses an adjacency matrix as a map. I would like to navigate the map by direction ex(N,E,S,W) my current attempt can only navigate via the name of the location
current output
You are currently in Foyer.
From this location, you could go to any of the following:
Living Room
Where would you like to go? Living Room
You are currently in Living Room.
From this location, you could go to any of the following:
Foyer
Bedroom 2
Powder Room
Kitchen
Where would you like to go? -__________________________________________________
I would like an output like
You are currently in Foyer.
From this location, you could go to any of the following:
South
Where would you like to go? South
You are currently in Living Room.
From this location, you could go to any of the following:
North
West
South
East
Where would you like to go?
import pygame
Inventory = []
names = ["Foyer", "Living Room", "Bedroom 2", "Full Bath", "Bedroom 3","Powder Room","Dinning", "Home Office", "Kitchen","Walkin Closet", "Hallway", "Bedroom1", "Sitting Room","Balcony", "Storage", "Garage", "Supply Closet", "Utility Closet", "Front Yard", "Sidewalk"]
graph = [[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0],[0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]]
directions =["North", "East", "South", "West"]
curr_location = "Foyer"
while True:
print("You are currently in ", curr_location, ".", sep = '')
print()
exits = []
print("From this location, you could go to any of the following:")
indx_location = names.index(curr_location)
for each in range(len(graph[indx_location])):
if graph[indx_location][each] == 1:
print("\t", names[each])
exits.append(names[each])
print()
next_location = input("Where would you like to go? ")
if not (next_location in exits):
print()
print("You cannot go this way.")
else:
curr_location = next_location
print()
Maybe add North, South, East, West to exits conditionally if it's possible to move in that direction?

Can't Set Primary Key Via Sqlalchemy But Can Via PGAdmin4

For the following dataframe:
LAD20CD LAD20NM BNG_E BNG_N ... LAT Shape__Area Shape__Length geometry
0 E07000154 Northampton 476495 260539 ... 52.237751 8.255064e+07 38381.688084 POLYGON ((-0.8091414142605670 52.2753276939684...
1 E07000246 Somerset West and Taunton 304960 130228 ... 51.063480 1.191178e+09 233156.429712 POLYGON ((-3.0538047490802600 51.2059417666536...
2 E07000040 East Devon 313790 96050 ... 50.757599 8.182959e+08 169999.596103 MULTIPOLYGON (((-3.0524230989883701 50.9082640...
3 E07000044 South Hams 270676 54036 ... 50.371948 8.921215e+08 234574.690559 POLYGON ((-3.5842498548751598 50.4777231181161...
4 E07000202 Ipswich 617161 244456 ... 52.055920 4.084468e+07 29187.875675 POLYGON ((1.1578388391924299 52.08875163594530...
5 E06000026 Plymouth 249945 58255 ... 50.404942 8.288777e+07 49419.795939 POLYGON ((-4.1230475222729899 50.3467427583020...
6 E07000079 Cotswold 402125 208209 ... 51.772549 1.167649e+09 275881.531075 POLYGON ((-1.6657543045486300 51.9874888219864...
7 E08000002 Bury 379658 410768 ... 53.593102 1.007527e+08 57024.343964 POLYGON ((-2.2717870687905002 53.6145142332618...
8 E07000084 Basingstoke and Deane 454508 151423 ... 51.259369 6.345992e+08 122971.049819 POLYGON ((-0.9861237505300590 51.3628482885656...
9 E07000078 Cheltenham 394925 222232 ... 51.898609 4.653884e+07 31000.684891 POLYGON ((-2.0102151915442801 51.9029244535680...
10 E07000126 South Ribble 352017 425840 ... 53.726749 1.151752e+08 66247.390716 POLYGON ((-2.5994877797848099 53.7814710235385...
11 E08000037 Gateshead 420168 559658 ... 54.931198 1.475563e+08 67934.528110 POLYGON ((-1.7697567363655600 54.9809837372463...
12 E07000068 Brentwood 558560 196070 ... 51.641079 1.530372e+08 62499.674509 POLYGON ((0.4023278825251010 51.65099490683400...
13 E08000026 Coventry 432807 279689 ... 52.414230 9.979901e+07 43481.405727 POLYGON ((-1.4590531741648900 52.4551580337384...
14 S12000029 South Lanarkshire 284634 636071 ... 55.604530 1.771616e+09 247590.081941 POLYGON ((-4.1070317994739796 55.8346525858565...
15 E07000029 Copeland 310871 508739 ... 54.466171 7.405896e+08 142439.232915 POLYGON ((-3.1671393240152499 54.4541106699468...
16 E08000034 Kirklees 414586 416223 ... 53.642330 4.053064e+08 106837.808449 POLYGON ((-1.6816208841975799 53.7564689245214...
17 E06000017 Rutland 492992 308655 ... 52.667648 3.921855e+08 96395.318751 POLYGON ((-0.4950258021289160 52.6402363852470...
18 E07000121 Lancaster 356896 464988 ... 54.079010 5.801983e+08 167797.392829 POLYGON ((-2.4608627348339200 54.2267161360627...
19 E08000025 Birmingham 408150 287352 ... 52.484039 2.690266e+08 88776.343219 POLYGON ((-1.7880812993329001 52.5878626088220..
I can successfully save the dataframe to Postgres using the following code:
# CONNECT TO POSTGRES.
conn_params_dict = {"user":"postgres",
"password":"postgres",
# FOR host, USE THE POSTGRES INSTANCE CONTAINER NAME, AS THE CONTAINER IP CAN CHANGE.
"host":"postgres",
"database":"github_projects"}
connect_alchemy = "postgresql+psycopg2://%s:%s#%s/%s" % (
conn_params_dict['user'],
conn_params_dict['password'],
conn_params_dict['host'],
conn_params_dict['database']
)
# CREATE POSTGRES ENGINE (CONNECTION POOL).
engine = create_engine(connect_alchemy)
# CONVERT geometry COLUMN FROM DTYPE geometry TO DTYPE object TO ALLOW DATAFRAME TO BE SAVED TO POSTGRES.
lad_gdf['geometry'] = lad_gdf['geometry'].apply(lambda x: wkt.dumps(x))
pd.DataFrame(lad_gdf).to_sql("shapefile_lad20", con = engine, if_exists='replace', index=True,
dtype={"lad20code":sqlalchemy.types.Text,
"lad20nm":sqlalchemy.types.Text,
"bng_e":sqlalchemy.types.Integer,
"bng_n":sqlalchemy.types.Integer,
"long":sqlalchemy.types.Float,
"lat":sqlalchemy.types.Float,
"shape__area":sqlalchemy.types.Float,
"shape__length":sqlalchemy.types.Float,
"geometry":sqlalchemy.types.Text
})
I then try to set the Primary Key using the following:
set_primary_key = engine.execute("""
ALTER TABLE shapefile_lad20 ADD PRIMARY KEY (lad20cd)
""")
set_primary_key.close()
But this fails and gives the error:
ProgrammingError: (psycopg2.errors.UndefinedColumn) column "lad20cd" of relation "shapefile_lad20" does not exist
The lad20cd attribute very much does exist. I tried changing the case to LAD20CD in case that was the issue but I got the same result.
Strangely, I can set LAD20CD as the Primary Key via the PGAdmin4 GUI so I am not sure what the issue is here?
I have to convert a geometry column from dtype = geometry to dtype = object so that I can save the dataframe to Postgres - could this step possibly be the cause?
Thanks

Setting distance Dimension in Or tools for vehicle routing problem

I am trying to solve a vehicle routing problem with 5 drivers for deliveries. I am using haversine and lat-long to calculate the distance matrix. I am new to OR tools, so following the vrp example.
The issues is that the out 0f 5 drivers, only routes are generated for 2 drivers and these routes are very long. I want to generate multiple shorter routes so that all the drivers are utilized. Can please check if I am setting some constraint wrong.
Can someone please explain, how to set "Distance" dimension and SetGlobalSpanCostCoefficient in google OR-tools. Here is the code and output.
from __future__ import print_function
import pandas as pd
import numpy as np
import googlemaps
import math
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
gmaps = googlemaps.Client(key='API Key')
def calculate_geocodes():
df = pd.read_csv("banglore_zone.csv")
df['lat'] = pd.Series(np.repeat(0, df.size), dtype=float)
df['long'] = pd.Series(np.repeat(0, df.size), dtype=float)
result = np.zeros([df.size, 2])
for index, row in df.iterrows():
# print(row['Address'])
geocode_result = gmaps.geocode(row['Address'])[0]
lat = (geocode_result['geometry']['location']['lat'])
lng = (geocode_result['geometry']['location']['lng'])
result[index] = lat, lng
df.lat[index] = lat
df.long[index] = lng
print("First step", df)
coords = df.as_matrix(columns=['lat', 'long'])
return coords, df
def calculate_distance_matrix(coordinates, gmaps):
distance_matrix = np.zeros(
(np.size(coordinates, 0), np.size(coordinates, 0))) # create an empty matrix for distance between all locations
for index in range(0, np.size(coordinates, 0)):
src = coordinates[index]
for ind in range(0, np.size(coordinates, 0)):
dst = coordinates[ind]
distance_matrix[index, ind] = distance(src[0], src[1], dst[0], dst[1])
return distance_matrix
def distance(lat1, long1, lat2, long2):
# Note: The formula used in this function is not exact, as it assumes
# the Earth is a perfect sphere.
# Mean radius of Earth in miles
radius_earth = 3959
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi / 180.0
phi1 = lat1 * degrees_to_radians
phi2 = lat2 * degrees_to_radians
lambda1 = long1 * degrees_to_radians
lambda2 = long2 * degrees_to_radians
dphi = phi2 - phi1
dlambda = lambda2 - lambda1
a = haversine(dphi) + math.cos(phi1) * math.cos(phi2) * haversine(dlambda)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = radius_earth * c
return d
def haversine(angle):
h = math.sin(angle / 2) ** 2
return h
def create_data_model(distance_matrix, number_of_vehicles, depot):
"""Stores the data for the problem."""
data = {}
data['distance_matrix'] = distance_matrix
print(distance_matrix)
data['num_vehicles'] = number_of_vehicles
data['depot'] = depot
return data
def print_solution(data, manager, routing, solution, address_dataframe):
"""Prints solution on console."""
max_route_distance = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} ---> '.format(address_dataframe.iloc[manager.IndexToNode(index), 0])
previous_index = index
index = solution.Value(routing.NextVar(index))
route_distance += routing.GetArcCostForVehicle(
previous_index, index, vehicle_id)
plan_output += '{}\n'.format(manager.IndexToNode(index))
plan_output += 'Distance of the route: {}m\n'.format(route_distance)
print(plan_output)
max_route_distance = max(route_distance, max_route_distance)
print('Maximum of the route distances: {}m'.format(max_route_distance))
def main():
coordinates, address_dataframe = calculate_geocodes()
distance_matrix = calculate_distance_matrix(coordinates, gmaps)
data = create_data_model(distance_matrix, 5, 0)
# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(
len(data['distance_matrix']), data['num_vehicles'], data['depot'])
# Create Routing Model.
routing = pywrapcp.RoutingModel(manager)
# Create and register a transit callback.
def distance_callback(from_index, to_index):
"""Returns the distance between the two nodes."""
# Convert from routing variable Index to distance matrix NodeIndex.
from_node = manager.IndexToNode(from_index)
to_node = manager.IndexToNode(to_index)
return data['distance_matrix'][from_node][to_node]
transit_callback_index = routing.RegisterTransitCallback(distance_callback)
# Define cost of each arc.
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
# Add Distance constraint.
dimension_name = 'Distance'
routing.AddDimension(
transit_callback_index,
0, # no slack
80, # vehicle maximum travel distance
True, # start cumul to zero
dimension_name)
distance_dimension = routing.GetDimensionOrDie(dimension_name)
distance_dimension.SetGlobalSpanCostCoefficient(100)
# Setting first solution heuristic.
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.local_search_metaheuristic = (
routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
search_parameters.time_limit.seconds = 120
search_parameters.log_search = False
# Solve the problem.
solution = routing.SolveWithParameters(search_parameters)
# Print solution on console.
if solution:
print_solution(data, manager, routing, solution, address_dataframe)
if __name__ == '__main__':
main()
And the distance matrix and output is -
> [[ 0. 0.31543319 3.36774402 ... 8.79765925 8.94261055
> 8.83759758] [ 0.31543319 0. 3.09418962 ... 8.81074289 8.95034082
> 8.84901702] [ 3.36774402 3.09418962 0. ... 10.87348059 10.97329493
> 10.89962072] ... [ 8.79765925 8.81074289 10.87348059 ... 0. 0.20726879
> 0.06082994] [ 8.94261055 8.95034082 10.97329493 ... 0.20726879 0.
> 0.1465572 ] [ 8.83759758 8.84901702 10.89962072 ... 0.06082994 0.1465572
> 0. ]] Route for vehicle 0: 3Embed software 10th Cross St, RBI Colony, Ganganagar, Bengaluru, Karnataka 560024 ---> 0 Distance of
> the route: 0m
>
> Route for vehicle 1: 3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 ---> 0 Distance of the route:
> 0m
>
> Route for vehicle 2: 3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 ---> Sindhi High School,
> Kempapura ---> Hoppers stop Building No.12, Krishnaja Avenue, Near
> Kogilu Cross, International Airport Road, Yelahanka, Bengaluru --->
> Kempegowda International Airport Bengaluru ---> mvit International
> Airport Road, Hunasamaranahalli, Yelahanka, Krishnadeveraya Nagar,
> Bengaluru ---> Canadian International School 4 & 20, Manchenahalli,
> Yelahanka, Bengaluru ---> brick factory RMZ Galleria, Office Block,
> Ground Floor, B.B. Road, Yelahanka ---> Jakkur Aerodrome Bellary
> Road, Post, Yelahanka, Bengaluru, Karnataka ---> Godrej Platinum
> International Airport Road, Hebbal, Bengaluru, Karnataka ---> Vidya
> Niketan School 30, Kempapura Main Road, Kempapura, Hebbal, Bengaluru,
> Karnataka ---> Atria Institute of Technology, 1st Main Rd, Ags
> Colony, Anandnagar, Hebbal, Bengaluru, Karnataka ---> 0 Distance of
> the route: 26m
>
> Route for vehicle 3: 3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 ---> Caffe cofee day CBI road
> banglore ---> 0 Distance of the route: 0m
>
> Route for vehicle 4: 3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 ---> RT Nagar Police station
> ---> bus stop mekhri circle banglore ---> Truffles 80 Feet Road, Jaladarsini Layout, Sanjaynagar Banglore ---> BEL circle banglore
> ---> Paragon Outlet Shivapura, Peenya, Bengaluru ---> Taj vivanta Yeshwantpur, Bengaluru ---> Orion Mall A Block, Brigade Gateway, Dr
> Rajkumar Rd, Malleshwaram, Bengaluru ---> brand factory Malleshwaram
> Banglore ---> Mantri Square Mall, Sampige Road, Malleshwaram,
> Bengaluru, Karnataka ---> Krantivira Sangolli Rayanna Bengaluru, M.G.
> Railway Colony, Majestic, Bengaluru ---> UB city banglore --->
> Brigade road banglore ---> MG Road metro station Banglore --->
> commercial street bangalore ---> Infantry Road, Beside Prestige
> Building, Tasker Town, Shivaji Nagar, Bengaluru, Karnataka --->
> Garuda Mall Magrath Rd, Ashok Nagar, Bengaluru ---> Brand Factory -
> Home Town Above HomeTown, Vanshee Towers, Survey No.92/4 3rd and 4th
> Floors, Outer Ring Rd, Marathahalli, Bengaluru ---> KLM Shopping
> Mall, Marathahalli Bridge Marathahalli ---> Favourite Shop HAL Old
> Airport Rd, Subbaiah Reddy Colony, Marathahalli Village, Marathahalli,
> Bengaluru ---> Max RPR Plaza, Varthur Rd, Marathahalli, Bengaluru
> ---> Pick 'n' Move Shop No. 102, Ground Floor, Varthur Rd, Marathahalli Village, Marathahalli, Bengaluru ---> Lotto Shoes 45/2,
> Varthur Rd, Marathahalli Village, Marathahalli, Bengaluru, Karnataka
> ---> The Raymond Shop Opp. Mga Hospital, Marathalli Main Road Near Ring Road Junction, Bengaluru, Karnataka ---> chinnaswamy stadium
> banglore ---> fun cinemas cunningham road Banglore ---> Cant station
> banglore ---> Radhakrishna Theatre 25, 1st Main Rd, Mattdahally, RT
> Nagar, Bengaluru ---> Presidency School Near R T Nagar, HMT Layout,
> Bengaluru, Karnataka ---> 0 Distance of the route: 20m
>
> Maximum of the route distances: 26m
You should reduce vehicle maximum travel distance. currently you set it to 80.
and your routes distances are 20 and 26.
routing.AddDimension(
transit_callback_index,
0, # no slack
80, # vehicle maximum travel distance
True, # start cumul to zero
dimension_name)
You can use global span cost which would reduce the longest route traveled by any vehicle.
Eg. use it on the distance dimension like distance_dimension.SetGlobalSpanCostCoefficient().
Pass a high integer value as an argument, which is greater than the sum of all costs. Try setting it to 1000 or so.

python pretty printing simple if

I have pretty printed a content in this way using this code. This code prints everything out, how do I print a specific location using IF ? Such as Upper Bukit Timah, West Coast...
Area: Upper Bukit Timah
Summary: Cloudy
Latitude: 1.356084
Longitude: 103.768873
Area: West Coast
Summary: Cloudy
Latitude: 1.30039493
Longitude: 103.7504196
Area: Woodlands
Summary: Cloudy
Latitude: 1.44043052
Longitude: 103.7878418
Area: Yishun
Summary: Cloudy
Latitude: 1.42738834
Longitude: 103.8290405
import urllib2
from BeautifulSoup import BeautifulStoneSoup #Using bs3
url="https://api.projectnimbus.org/neaodataservice.svc/NowcastSet"
request = urllib2.Request(url)
request.add_header("accept", "*/*")
request.add_header('AccountKey', "OSJeROQjTg4v7Ec3kiecjw==")
request.add_header('UniqueUserID', "00000000000000000000000000000001")
result = urllib2.urlopen(request)
xml_str = result.read()
soup = BeautifulStoneSoup(xml_str)
prop_list = []
for content in soup.findAll("m:properties"):
props = {}
for prop in content.findChildren():
props[prop.name[2:]] = prop.text
prop_list.append(props)
for prop in sorted(prop_list):
print "Area: %(area)s\nSummary: %(summary)s\nLatitude: %(latitude)s\nLongitude: %(longitude)s\n" % prop
Well, you'd have to add an if statement to your final for loop, checking whether the current entry in in some positive list. Something like this:
areas_to_print = ["Upper Bukit Timah", "West Coast", "Woodlands", "Yishun"]
for prop in sorted(prop_list):
if prop["area"] in areas_to_print:
print "Area: %(area)s\nSummary: %(summary)s\nLatitude: %(latitude)s\nLongitude: %(longitude)s\n" % prop
Alternatively, you could just as well add that same if statement to your first for loop, so only those entries are added to the prop_list in the first place.
for prop in sorted(prop_list):
if (prop["area"] == "whatever u wnt or someother condition"):
print "Area: %(area)s\nSummary: %(summary)s\nLatitude: %(latitude)s\nLongitude: %(longitude)s\n" % prop

Categories