import glob import pandas as pd import os def sanitize_urls_in_instances(root_folder, filename, url_containing_columns): """ Iterates through all "instances.csv" files in subfolders of the given root folder, reads them into pandas DataFrames, and replaces dots (".") in URLs within the specified columns with "[DOT]". Saves the modified DataFrames back to the same files. Args: root_folder (str): The path to the root folder containing the subfolders with "instances.csv" files. url_containing_columns (list): A list of column names that might contain URLs. """ pattern = os.path.join(root_folder, "**", filename) file_paths = glob.glob(pattern, recursive=True) if not file_paths: print(f"No {filename} files found under the root folder: {root_folder}") return print(file_paths) resp = input("Are the paths OK? [y/n] ") if not resp == "y": return for file_path in file_paths: try: print(f"Processing file: {file_path}") df = pd.read_csv(file_path) changed = False for col in url_containing_columns: if col in df.columns: if (df[col].str.contains(r"\.")).any(): df[col] = df[col].str.replace(".", "[DOT]") print(f" Sanitized URLs in column: {col}") changed = True else: print(f" Column {col} already sanitized") else: print(f" Column '{col}' not found in this file.") if changed: df.to_csv(file_path, index=False) except FileNotFoundError: print(f"Error: File not found at {file_path}") except Exception as e: print(f"An error occurred while processing {file_path}: {e}") instances_cols_with_url = ["host", "Id", "Label"] interactions_cols_with_url = ["Source", "Target"] sanitize_urls_in_instances("./", "instances.csv", instances_cols_with_url) sanitize_urls_in_instances("./", "interactions.csv", interactions_cols_with_url)