Datasets:
Tags:
Not-For-All-Audiences
Upload remove_bad_symbols_from_zipped_text_files.ipynb
Browse files
remove_bad_symbols_from_zipped_text_files.ipynb
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"mount_file_id":"1rRSp-CodaL6NO83MqOa_mFj1UT045VCx","authorship_tag":"ABX9TyM1LlYGCNQ9uXEHkY7UHdAi"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"43b480a5","outputId":"093358b8-6aa7-4770-e03f-f592bdde5f74"},"source":["import os\n","import re\n","import zipfile\n","import shutil\n","\n","# Define paths\n","zip_path = '/content/drive/MyDrive/characters/descriptions_archive.zip'\n","extract_dir = '/content/extracted_descriptions'\n","output_dir = '/content/processed_descriptions'\n","output_zip_path = '/content/drive/MyDrive/processed_descriptions_archive.zip'\n","\n","# Unpack the zip file\n","print(\"Unpacking zip file...\")\n","with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n","\n","# Create output directory\n","os.makedirs(output_dir, exist_ok=True)\n","\n","# Regex pattern to match allowed characters: a-zA-Z0-9 and . ! ? | _ , and spaces\n","# a-zA-Z0-9 is letters and numbers.\n","# Other allowed characters: . ! ? | _ , space\n","allowed_pattern = re.compile(r'[^a-zA-Z0-9.!_?|,\\s]')\n","\n","print(\"Processing text files...\")\n","for root, dirs, files in os.walk(extract_dir):\n"," for file in files:\n"," if file.endswith('.txt'):\n"," file_path = os.path.join(root, file)\n","\n"," # Read original content\n"," with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:\n"," content = f.read()\n","\n"," # Remove all characters that are not allowed\n"," cleaned_content = allowed_pattern.sub('', content)\n","\n"," # Enclose the text inside brackets {}\n"," formatted_content = f\"{{{cleaned_content}}}\"\n","\n"," # Save to the new output folder with relative structure\n"," rel_path = os.path.relpath(file_path, extract_dir)\n"," out_file_path = os.path.join(output_dir, rel_path)\n"," os.makedirs(os.path.dirname(out_file_path), exist_ok=True)\n","\n"," with open(out_file_path, 'w', encoding='utf-8') as f:\n"," f.write(formatted_content)\n","\n","# Zip the results\n","print(\"Zipping processed results...\")\n","shutil.make_archive(output_zip_path.replace('.zip', ''), 'zip', output_dir)\n","\n","print(f\"Processing complete! Saved to {output_zip_path}\")"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Unpacking zip file...\n","Processing text files...\n","Zipping processed results...\n"]}]}]}
|