Python新手求助:实现批量替换文本缩略语并导出至指定目录
Fixing Your Contraction Replacement Script
Hey there! Let's get your Python script working smoothly for replacing contractions in all .txt files under ./test and saving the processed files to a new directory. Here's a polished, working version of your code with clear explanations:
import os import contractions # Define input and output directories (adjust these paths if needed) input_dir = "./test" output_dir = "./processed_files" # Create the output directory if it doesn't already exist os.makedirs(output_dir, exist_ok=True) # Get full paths to all .txt files in the input directory txt_files = [ os.path.join(input_dir, filename) for filename in os.listdir(input_dir) if filename.endswith('.txt') ] # Process each file one by one for file_path in txt_files: # Extract just the filename to use for the output file filename = os.path.basename(file_path) output_file_path = os.path.join(output_dir, filename) # Read the content of the original file with open(file_path, 'r', encoding='utf-8') as input_file: original_content = input_file.read() # Replace contractions using the contractions library processed_content = contractions.fix(original_content) # Write the cleaned content to the output file with open(output_file_path, 'w', encoding='utf-8') as output_file: output_file.write(processed_content) print(f"Done! Processed {len(txt_files)} files. Results saved to {output_dir}")
Key Fixes & Explanations:
- Full File Paths: Used
os.path.join()to create complete paths for input files—your original code tried to open filenames without their directory path, which would cause errors. - Output Directory Setup: Added
os.makedirs(output_dir, exist_ok=True)to automatically create the output folder if it doesn't exist (no more "directory not found" crashes). - Loop Through Files: Added a
forloop to handle each.txtfile individually—your initial code tried to open a list of files directly, which isn't valid. - Safe File Handling: Used
with open(...)context managers for reading/writing files—this ensures files are properly closed after operations, even if an error occurs. - Encoding Support: Specified
encoding='utf-8'to avoid garbled text when dealing with special characters in files. - Contraction Replacement: Used
contractions.fix()—the standard method from the library to replace common contractions like "don't" → "do not" or "I'm" → "I am".
Quick Note:
If you haven't installed the contractions library yet, run this command in your terminal first:
pip install contractions
内容的提问来源于stack exchange,提问作者Rowland
相关产品推荐
相关产品推荐

