I have Python code for parsing STR files to a Pandas Dataframe object.
I want to extend the code so that I can run it on a directory of text files (and also on SRTs, so just make it more general).
I will attach below the code and an example of part of a text file.
def read_srt_files_to_df(directory_path, out_name="raw_data", merge_subtitles=True):
"""
Reads all SRT files in the specified directory and combines them into a DataFrame.
code
Parameters:
directory_path (str): Path to the directory containing SRT files
merge_subtitles (bool): If True, merges all subtitles for each file into a single text
Returns:
pandas.DataFrame: DataFrame containing subtitle data.
If merge_subtitles is True, returns one row per file with merged text.
Otherwise, returns detailed subtitle information.
"""
# if raw data file already exists, return it
if Path(f"{out_name}.csv").exists():
return pd.read_csv(f"{out_name}.csv")
# Convert string path to Path object
directory = Path(directory_path)
# List to store data from all files
all_subtitle_data = []
# Get all .srt files in the directory
srt_files = list(directory.glob('*.srt'))
if not srt_files:
raise ValueError(f"No SRT files found in directory: {directory_path}")
# Process each SRT file
for srt_file in srt_files:
try:
# Read the SRT file
subtitles = pysrt.open(srt_file)
# Extract data from each subtitle
for sub in subtitles:
subtitle_data = {
'filename': srt_file.name,
'index': sub.index,
'start_time': sub.start.to_time(),
'end_time': sub.end.to_time(),
'text': sub.text.strip()
}
all_subtitle_data.append(subtitle_data)
except Exception as e:
print(f"Error processing file {srt_file}: {str(e)}")
# Create DataFrame from collected data
df = pd.DataFrame(all_subtitle_data)
if merge_subtitles and not df.empty:
# Merge texts for each file
merged_df = df.groupby('filename').agg({
'text': lambda x: ' '.join(x),
'start_time': 'first',
'end_time': 'last',
'index': 'count'
}).reset_index()
# Rename index column
res = merged_df.rename(columns={'index': 'subtitle_length'})
else:
# If not merging or df is empty, return original format
res = df.sort_values(['filename', 'index']).reset_index(drop=True)
# save raw data to a csv file
res.to_csv(f"{out_name}.csv", encoding='utf-8')
return res
Assistant
"""
תתחילי. ידעתי שאתה תגיד, אבל רציתי להגיד שאתה תתחילי. אני הגעתי לכפר עזה אחרי השירות הצבאי שלי בשנת 1970. אני וגוגו דוד גולדשטיין נישאנו ב-1971.
נולדו לנו ארבעה ילדים, נדב הבכור,
נעמה, ניצן וענבר, ויש לנו כיום עשרה נכדים, שמונה מהם בכפר עזה,
ושניים בעין החורש. במהלך ה-53 שנים בכפר עזה
עבדתי בכל מה שאפשר היה לעבוד אז בקיבוץ, ברפת, בלול, בכדר אוכל וכו' וכו'.
אחר כך, במהלך השנים, הייתי בתחילת שנות ה-90 מזכירת קיבוץ כפר עזה, במשך שלוש שנים, ואחר כך יצאתי לעבודה במועצה אזורית שער הנגב. עבדתי שם 16 שנים בתפקיד של גייסת כספים לעמותות של המועצה. אוקיי, אז אני הגעתי לכפר עזה במסגרת גרעין נחל, אחרי שירות בנחל המוצנח. זה היה ב-1970.
ניסינו ב-1971. ורדה כבר מסעה את הפרטים, אז אין לי מה לחזור עליהם. במהלך ה-53 שנה שאני בכפר עזה מילאתי תפקידים ציבוריים, כמו מרכז משק וכו'. אחרי זה הייתי במשך למעלה מ-30 שנה מרכז רכש של מפעל כפרית, מפעל ציבורי שנסחר בבורסה, שיש לו שישה מפעלים בעולם.
ב-2017 יצאתי לפנסיה, אבל המשכתי לעבוד באופן חלקי
מתוקף העניין שאני גר בכפר עזה והמפעל הוא ממש ב-200 מטר, ועשיתי ליווי של פרויקטים. גם היום אני ממשיך לעבוד מכאן באופן חלקי למען הנשמה יותר,
עקב כל מה שקרה לנו. אבל כן, אני גם פעיל מבחינה ציבורית עד היום בכפר עזה, בכל מיני נושאים.
אני מבקש לחזור לימים שלפני השביעים. יש לכם זיכרונות מהשישי או מהחמישי לאוקטובר.
בסך הכל היינו משפחה מאוד גדולה, היינו שבט בכפר עזה, אנחנו ועוד שני ילדים, כאילו הבכורים נעמה ונדב ובני המשפחה שלהם ועוד שמונה נכדים וגם ההורים של הכלה שלנו.
משפחה מאוד מחוברת, מאוד תומכת. היינו בסך הכול קרובים אחד לשני, אז הייתה מצד אחד נגישות לנכדים ולילדים, ומצד שני גם אפשרות להגיד להם תודה רבה, תבכו בבית, אצל סבא וסבתא לא בוכים. כל יום שישי היינו נפגשים אצלנו לארוחות שישים גדולות מאוד, שולחן פתוח לכל המשפחה וגם לחברים וגם לאורחים אחרים. כן, הבית שלנו היה ידוע בצבעוניות שלו, באוספים שלו מכל העולם, בטיולים שטיילנו במחוזות גבוהים עד ההימאליה ועד עמק קטמנדו ואפריקה וכל העולם ואחותו.
ובגלל שאני גם מצלמת, אז הבית הזה היה מלא צבעים וזיכרונות, ובאמת
הוא היה יפה, הוא היה צבעוני, הוא היה חם, הוא היה מלכד.
זה מה שהיה באופן כללי. הימים שקדמו ל-7 באוקטובר,
הבן שלנו, נדב, היה טריאטלט, והוא התכונן לאיזושהי תחרות, והוא נפגע בתאונת דרכים. משאית עלתה עליו ב-26 ב-7 באוקטובר, הוא נפצע מאוד מאוד קשה. הוא עבר שני ניתוחים, בירך, בגב, ושבר צלעות.
אז אני יכולה להגיד שהפעם הראשונה שהוא, אחרי שיקום מאוד אינטנסיבי, בערב ראש השנה הוא נכנס הביתה פעם ראשונה בלי קביים, אחרי שלושה חודשי שיקום מאוד מאוד קשים.
זאת הייתה הפעם האחרונה שכל המשפחה שלנו הייתה ביחד, אני לא יודעת למה ואיך, וזו הייתה איזושהי תחושה שחייבים לעשות צילום משפחתי כזה גדול כמו של פעם. כולם התיישבו על הספה, השורות, למעלה, למטה, הכלב.
וזאת הייתה בעצם הפעם האחרונה ש... אתם יכולים לצלם אותו. אחרי זה נשמח, נביא אותם ונצלם אותו בסוף. אז זו הייתה ארוחה גדולה שהייתה לנו בערב ראש השנה. ואחר כך, בערב חג סוכות ראשון, כן, הייתה לנו ארוחה קצת טובה. יותר קטנה, אבל נדב והמשפחה שלו היו, נעמה לא הייתה.
וזהו, וזאת הייתה הפעם האחרונה בעצם שהשולחן בבית נפתח לגדלים בלתי אפשריים, מלאים באוכל ובכיף ובשמחה.
כן, שבוע ימים אחרי זה קרה האסון הגדול, השבת השחורה.
וזהו, ומאז, כן, התהפכו החיים שלנו. הם כבר לא יהיו יותר מה שהם היו, אם כי אנחנו מאוד מאוד משתדלים,
באין בית הזה, לשמור על הבית כמה שאפשר. זהו. אני רק עושה...
לגבי הבית, כמו שאמרתי קודם, שאומרים לי, בית בונים מחדש.
"""
Got it! You want your existing function to:
Work not just on .srt files but on any text-based file (like .txt).
Keep the option to merge subtitles (or text blocks) per file.
Be more general for a directory of text files, not just SRTs.
I’ve rewritten and generalized your function. It can now handle both .srt and .txt files. For SRT files, it keeps the timestamp info; for plain text files, it just reads the content.
Here’s an updated version:
pythonCopy codeimport pandas as pd
from pathlib import Path
import pysrt
def read_text_and_srt_files_to_df(directory_path, out_name="raw_data", merge_text=True):
"""
Reads all SRT and TXT files in the specified directory and combines them into a DataFrame.
code
Parameters:
directory_path (str): Path to the directory containing files
merge_text (bool): If True, merges all subtitles/text for each file into a single text
Returns:
pandas.DataFrame: DataFrame containing file data.
If merge_text is True, returns one row per file with merged text.
Otherwise, returns detailed information for SRT files, or one row per TXT file.
"""
directory = Path(directory_path)
if Path(f"{out_name}.csv").exists():
return pd.read_csv(f"{out_name}.csv")
all_data = []
# Collect all .srt and .txt files
files = list(directory.glob("*.srt")) + list(directory.glob("*.txt"))
if not files:
raise ValueError(f"No SRT or TXT files found in directory: {directory_path}")
for file in files:
try:
if file.suffix.lower() == ".srt":
# Read SRT file
subtitles = pysrt.open(file)
for sub in subtitles:
all_data.append({
'filename': file.name,
'index': sub.index,
'start_time': sub.start.to_time(),
'end_time': sub.end.to_time(),
'text': sub.text.strip()
})
else:
# Read TXT file
with open(file, encoding="utf-8") as f:
text = f.read().strip()
all_data.append({
'filename': file.name,
'index': 1,
'start_time': None,
'end_time': None,
'text': text
})
except Exception as e:
print(f"Error processing file {file}: {e}")
df = pd.DataFrame(all_data)
if merge_text and not df.empty:
merged_df = df.groupby('filename').agg({
'text': lambda x: ' '.join(x),
'start_time': 'first',
'end_time': 'last',
'index': 'count'
}).reset_index()
res = merged_df.rename(columns={'index': 'text_length'})
else:
res = df.sort_values(['filename', 'index']).reset_index(drop=True)
res.to_csv(f"{out_name}.csv", encoding='utf-8', index=False)
return res
✅ Key Improvements:
Works for both .srt and .txt files.
For TXT files, start_time and end_time are None.
Keeps the merge_text option.
Saves the result as a CSV for easy reuse.
If you want, I can also enhance it further so it can recursively scan subfolders and detect other text-like formats automatically, making it fully directory-agnostic.
Do you want me to do that next?