79 lines
2.7 KiB
Python
Executable file
79 lines
2.7 KiB
Python
Executable file
#!/usr/bin/env python
|
|
# Script Name: remove-utm
|
|
|
|
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 process_csv_file_remove_tracking_params(file_path):
|
|
"""Remove UTM, CID, and CMMMC parameters from URLs in the given CSV file."""
|
|
with open(file_path, 'r') as file:
|
|
reader = csv.reader(file)
|
|
rows = list(reader)
|
|
|
|
if not rows:
|
|
return
|
|
|
|
modified_rows = []
|
|
for row in rows:
|
|
modified_row = []
|
|
for cell in row:
|
|
if "?utm" in cell:
|
|
modified_cell = cell.split("?utm")[0]
|
|
elif "?cid" in cell:
|
|
modified_cell = cell.split("?cid")[0]
|
|
elif "?cm_mmc" in cell:
|
|
modified_cell = cell.split("?cm_mmc")[0]
|
|
else:
|
|
modified_cell = cell
|
|
modified_row.append(modified_cell)
|
|
modified_rows.append(modified_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 remove UTM, CID, and CMMMC parameters from URLs."""
|
|
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)
|
|
process_csv_file_remove_tracking_params(file_path)
|
|
spinner.succeed(f'Finished processing {state_dir}')
|
|
|
|
def main():
|
|
figlet = Figlet(font='slant')
|
|
script_name = "remove-utm".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"Removing tracking parameters in {STAGE_2_DIRECTORY}...")
|
|
process_csv_files(STAGE_2_DIRECTORY)
|
|
|
|
final_spinner = Halo(spinner='dots', color='green')
|
|
final_spinner.start()
|
|
final_spinner.succeed("Tracking parameters removed.")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|