85 lines
2.8 KiB
Python
Executable file
85 lines
2.8 KiB
Python
Executable file
#!/usr/bin/env python
|
|
# Script Name: sanitize-gbp-business-website
|
|
|
|
import os
|
|
import csv
|
|
import sys
|
|
from pyfiglet import Figlet
|
|
from halo import Halo
|
|
|
|
# Define the paths based on the project details
|
|
PROJECT_ROOT = "/home/ld/mgk-scrapes"
|
|
CURRENT_DATASET = os.path.join(PROJECT_ROOT, "current-data")
|
|
DATA_DIRECTORY = os.path.join(CURRENT_DATASET, ".data")
|
|
STAGE_2_DIRECTORY = os.path.join(DATA_DIRECTORY, "stage-2")
|
|
|
|
def sanitize_website_data(file_path):
|
|
"""Sanitize website data in the given CSV file."""
|
|
new_column_name = 'GBP Business Website'
|
|
|
|
with open(file_path, 'r') as file:
|
|
reader = csv.reader(file)
|
|
rows = list(reader)
|
|
|
|
if not rows:
|
|
return
|
|
|
|
headers = rows[0]
|
|
if new_column_name not in headers:
|
|
headers.append(new_column_name)
|
|
new_column_index = headers.index(new_column_name)
|
|
|
|
data_rows = rows[1:]
|
|
modified_rows = [headers]
|
|
|
|
for row in data_rows:
|
|
new_row = row[:]
|
|
while len(new_row) <= new_column_index:
|
|
new_row.append('')
|
|
for i, cell in enumerate(row):
|
|
if cell.startswith('http://') or cell.startswith('https://'):
|
|
new_row[new_column_index] = cell
|
|
new_row[i] = ''
|
|
break
|
|
modified_rows.append(new_row)
|
|
|
|
with open(file_path, 'w', newline='') as file:
|
|
writer = csv.writer(file)
|
|
writer.writerows(modified_rows)
|
|
|
|
def process_csv_files(stage_directory):
|
|
"""Process all CSV files in the given stage directory to sanitize website data."""
|
|
for state_dir in os.listdir(stage_directory):
|
|
state_path = os.path.join(stage_directory, state_dir)
|
|
if os.path.isdir(state_path):
|
|
spinner = Halo(text=f'Processing {state_dir}', spinner='dots')
|
|
spinner.start()
|
|
for county_dir in os.listdir(state_path):
|
|
county_path = os.path.join(state_path, county_dir)
|
|
if os.path.isdir(county_path):
|
|
csv_files = [file for file in os.listdir(county_path) if file.endswith('.csv')]
|
|
for file in csv_files:
|
|
file_path = os.path.join(county_path, file)
|
|
sanitize_website_data(file_path)
|
|
spinner.succeed(f'Finished processing {state_dir}')
|
|
|
|
def main():
|
|
figlet = Figlet(font='slant')
|
|
script_name = "sanitize-gbp-business-website".replace("-", " ").title()
|
|
print(figlet.renderText(script_name))
|
|
|
|
if not os.path.exists(STAGE_2_DIRECTORY):
|
|
print(f"Error: The directory {STAGE_2_DIRECTORY} does not exist.")
|
|
sys.exit(1)
|
|
|
|
print(f"Sanitizing website data in {STAGE_2_DIRECTORY}...")
|
|
process_csv_files(STAGE_2_DIRECTORY)
|
|
|
|
final_spinner = Halo(spinner='dots', color='green')
|
|
final_spinner.start()
|
|
final_spinner.succeed("Website data sanitized.")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|