Skip to content

Instantly share code, notes, and snippets.

@AO8
Last active February 7, 2019 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AO8/2d33ded5744d57d51c3cdd982da98566 to your computer and use it in GitHub Desktop.
Save AO8/2d33ded5744d57d51c3cdd982da98566 to your computer and use it in GitHub Desktop.
Auburn, WA crime analyzer with Python 3. This small project provided an exercise in working with CSV files and open data from the City of Auburn.
# Auburn, WA Police Data CSV available at: https://data.auburnwa.gov/
import csv
import sys
from collections import Counter
from datetime import datetime as dt
# Rows in CSV file for reference:
# [0] CASENUMBER
# [1] OFFENSE
# [2] OFFENSETYPE
# [3] OFFENSENAME,
# [4] REPORTED
# [5] REPORTINGDISTRICT
# [6] Location
def main():
csv_file = "Crimes.csv"
total = get_crime_total(csv_file)
crime_count = get_crime_count(csv_file)
crime_dates = get_crime_dates(csv_file)
print_results(total, crime_count, crime_dates)
def get_crime_total(filename):
"""get crime totals from csv file"""
with open(filename, "r", encoding="utf-8") as f:
reader = csv.reader(f)
row_count = sum(1 for row in reader) - 1 # minus headings
return row_count
def get_crime_dates(filename):
"""get crime report date data from csv file"""
dates = Counter()
with open("Crimes.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
items = row["REPORTED"].split()
date = items[0]
year = date[-4:]
dates[year] += 1
return dates
def get_crime_count(filename):
"""get crime data from csv file"""
crimes = Counter()
with open("Crimes.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
crimes[row["OFFENSENAME"]] += 1
return crimes
def print_results(total, crime_dict, crime_dates):
"""Print total crimes; top 10 crimes; and crime by year"""
print(" TOTAL CRIMES REPORTED ".center(79, "-"))
print(f"\n\t{total} crimes were reported in Auburn from 2017 to the present.\n",
file=sys.stderr)
print(" TOP 10 CRIME TYPES ".center(79, "-"))
print()
for crime, count in crime_dict.most_common(10):
print(f"\t{crime} = {count}", file=sys.stderr)
print()
print(" CRIMES BY YEAR ".center(79, "-"))
print(f"\n\t2017 = {crime_dates['2017']}", file=sys.stderr)
print(f"\t2018 = {crime_dates['2018']}", file=sys.stderr)
print(f"\t2019 = {crime_dates['2019']} as of {dt.today().strftime('%x')}",
file=sys.stderr)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment