-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_schools.py
More file actions
98 lines (82 loc) · 3.86 KB
/
search_schools.py
File metadata and controls
98 lines (82 loc) · 3.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import json
import os
import argparse
# Define path relative to the script location
script_dir = os.path.dirname(os.path.abspath(__file__))
data_file_path = os.path.join(script_dir, 'data', 'school_data_final.json')
def load_data(file_path):
"""Loads school data from the JSON file."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
if 'schools' in data and isinstance(data['schools'], list):
return data['schools']
else:
print(f"Error: 'schools' key not found or is not a list in {file_path}")
return []
except FileNotFoundError:
print(f"Error: Data file not found at {file_path}")
return []
except json.JSONDecodeError:
print(f"Error: Could not decode JSON from {file_path}")
return []
except Exception as e:
print(f"An unexpected error occurred while loading data: {e}")
return []
def search_schools(schools, name=None, min_rank=None, max_rank=None, suburb=None, school_type=None):
"""Searches and filters the list of schools based on provided criteria."""
results = schools
if name:
results = [s for s in results if name.lower() in s.get('name', '').lower()]
# Filter by rank range
if min_rank is not None:
try:
min_r = int(min_rank)
results = [s for s in results if s.get('rank') is not None and s.get('rank') >= min_r]
except ValueError:
print("Warning: Invalid minimum rank provided. Rank must be an integer.")
if max_rank is not None:
try:
max_r = int(max_rank)
results = [s for s in results if s.get('rank') is not None and s.get('rank') <= max_r]
except ValueError:
print("Warning: Invalid maximum rank provided. Rank must be an integer.")
if suburb:
results = [s for s in results if suburb.lower() in s.get('suburb_name', '').lower()]
if school_type:
results = [s for s in results if school_type.lower() == s.get('type', '').lower()]
return results
def display_results(results):
"""Prints the search results in a readable format."""
if not results:
print("No schools found matching your criteria.")
return
print(f"\nFound {len(results)} school(s):")
print("-" * 30)
for school in results:
print(f" Name: {school.get('name', 'N/A')}")
print(f" Rank: {school.get('rank', 'N/A')}")
print(f" Type: {school.get('type', 'N/A')}")
print(f" Suburb: {school.get('suburb_name', 'N/A')} (Postcode: {school.get('suburb', 'N/A')})")
print(f" Score 2023: {school.get('score_2023', 'N/A')}")
print("-" * 30)
def main():
parser = argparse.ArgumentParser(description='Search and filter schools in the dataset.')
parser.add_argument('-n', '--name', help='Filter by school name (partial match)')
parser.add_argument('--min-rank', help='Filter by minimum rank (inclusive)')
parser.add_argument('--max-rank', help='Filter by maximum rank (inclusive)')
parser.add_argument('-s', '--suburb', help='Filter by suburb name (partial match)')
parser.add_argument('-t', '--type', help='Filter by school type (exact match, e.g., Public, Catholic, Independent/Private)')
args = parser.parse_args()
# Check if at least one filter is provided
if not any([args.name, args.min_rank, args.max_rank, args.suburb, args.type]):
parser.print_help()
print("\nPlease provide at least one filter criterion.")
return
all_schools = load_data(data_file_path)
if not all_schools:
return # Error message already printed by load_data
found_schools = search_schools(all_schools, name=args.name, min_rank=args.min_rank, max_rank=args.max_rank, suburb=args.suburb, school_type=args.type)
display_results(found_schools)
if __name__ == "__main__":
main()