Implement: def preprocesstextfiles(dirname, cleandir="cleanedinterviews"): """ Make a…
- User
Implement:
def preprocess_textfiles(dir_name, clean_dir="cleaned_interviews"): """ Make a new directory called cleaned_interviews in the given directory For each of the text files in the directory 1. remove the signature at the end of the text (if it exists) 2. remove any rows with only digits and spaces 3. remove newlines that are not preceded by a period 4. save the cleaned text file in the cleaned_interviews directory with the same filename :param dir_name: :return: """ pass
- Assistant
Here’s a robust implementation for your preprocess_textfiles function: pythonCopy codeimport os import re
def preprocess_textfiles(dir_name, clean_dir="cleaned_interviews"): """ Make a new directory called cleaned_interviews in the given directory. For each of the text files in the directory: 1. remove the signature at the end of the text (if it exists) 2. remove any rows with only digits and spaces 3. remove newlines that are not preceded by a period 4. save the cleaned text file in the cleaned_interviews directory with the same filename :param dir_name: path to directory containing text files :param clean_dir: subdirectory to save cleaned files :return: None """ # Create output directory if it doesn't exist clean_path = os.path.join(dir_name, clean_dir) os.makedirs(clean_path, exist_ok=True)
- User
Why didn't it capture the first line here?
1 ניצן בן שושן: אני ניצן בן שושן.
2 נולדתי ב-1942 בהרי האטלס במרוקו.
3 למדתי עברית וצרפתית ותלמוד תורה במרוקו.
- Assistant
I see the problem 👍 The regex I gave for removing digit-only lines was: pythonCopy codere.sub(r"^\s*\d+\s*$", "", text, flags=re.MULTILINE)
But in your file the very first line is: Copy code1
That’s not just "1" — it starts with a BOM (Byte Order Mark) character (\ufeff, invisible in most editors, but that leading "" gives it away). So the regex doesn’t match because \ufeff is in front of the digit.
Fix We need to account for BOMs or other hidden chars at the start of lines. Two easy options: Option 1: Normalize BOM before regex pythonCopy codetext = text.replace("\ufeff", "") text = re.sub(r"^\s*\d+\s*$", "", text, flags=re.MULTILINE)
Option 2: Make regex tolerant pythonCopy codetext = re.sub(r"^[^\S\r\n]\ufeff?\s\d+\s*$", "", text, flags=re.MULTILINE)
Updated snippet in context pythonCopy code# Remove BOM just in case text = text.replace("\ufeff", "")
Remove rows with only digits and spaces
text = re.sub(r"^\s*\d+\s*$", "", text, flags=re.MULTILINE)
That will correctly remove the leading 1 line in your sample.
Do you want me to also strip those numbering lines when they’re followed by a sentence on the same line (e.g. "1 ניצן בן שושן: ..."), or only if the line has just a number?