특정 디렉토리에서 특정 파일들을 추출해서 정제후 Pickle 및 리스트로 리턴하는 함수

특정 디렉토리에서 특정 파일들을 추출해서 정제후 Pickle 및 리스트로 리턴하는 함수
Photo by Nick Harsell / Unsplash
import os  
import re  
import time  
import pickle  
  
def preProcessNote(file, path_dir):  
    try:  
        file_path = os.path.join(path_dir, file)  
        with open(file_path, 'r', encoding='utf-8') as f:  
            lines = f.readlines()  
  
        # 지워야 할 지점 체크  
        start_idx = None  
        end_idx = None  
        for idx, line in enumerate(lines):  
            if re.match('---', line):  
                if start_idx is None:  
                    start_idx = idx  
                else:  
                    end_idx = idx  
                    break  
  
        if start_idx is None or end_idx is None:  
            raise ValueError(f"Start or end delimiter not found in file: {file_path}")  
  
        # 삭제하기  
        lines = lines[:start_idx] + lines[end_idx+1:]  
        note = ''.join(lines)  
  
        # 데이터 정제  
        note = re.sub(r'[\n\t]+', '', note)  
  
        return note  
  
    except FileNotFoundError as e:  
        raise FileNotFoundError(f"File not found: {file_path}") from e  
    except PermissionError as e:  
        raise PermissionError(f"Permission denied for file: {file_path}") from e  
    except UnicodeDecodeError as e:  
        raise UnicodeDecodeError(f"Error decoding file: {file_path}. Ensure the file is UTF-8 encoded.") from e  
    except ValueError as e:  
        raise ValueError(f"Processing error in file {file_path}: {str(e)}") from e  
    except OSError as e:  
        raise OSError(f"OS error occurred while processing file: {file_path}") from e  
    except Exception as e:  
        raise Exception(f"Unexpected error while processing file: {file_path}") from e  
  
def preProcessNotes(path_dir="data/md", file_ext="md", output_dir="output", output_filename="notes.pkl"):  
    start_time = time.time()  # 시작 시간 기록  
  
    try:  
        # 파일 리스트 가지고 오기  
        file_list = os.listdir(path_dir)  
        file_list = [file for file in file_list if file.endswith(f'.{file_ext}')]  
    except FileNotFoundError as e:  
        raise FileNotFoundError(f"Directory not found: {path_dir}") from e  
    except PermissionError as e:  
        raise PermissionError(f"Permission denied for directory: {path_dir}") from e  
    except OSError as e:  
        raise OSError(f"OS error occurred while accessing directory: {path_dir}") from e  
    except Exception as e:  
        raise Exception(f"Unexpected error while listing files in directory: {path_dir}") from e  
  
    # 출력 디렉토리 생성  
    if not os.path.exists(output_dir):  
        try:  
            os.makedirs(output_dir)  
        except OSError as e:  
            raise OSError(f"Failed to create output directory: {output_dir}") from e  
  
    notes = []  
  
    for file in file_list:  
        try:  
            note = preProcessNote(file, path_dir)  
            notes.append(note)  
        except Exception as e:  
            print(f"Error occurred while processing {file}: {e}")  
  
    # notes 리스트를 pickle 파일로 저장  
    output_file_path = os.path.join(output_dir, output_filename)  
    try:  
        with open(output_file_path, 'wb') as pkl_file:  
            pickle.dump(notes, pkl_file)  
    except Exception as e:  
        raise Exception(f"Failed to save notes to pickle file: {output_file_path}") from e  
  
    end_time = time.time()  # 종료 시간 기록  
    elapsed_time = end_time - start_time  # 경과 시간 계산  
  
    print(f"Processing completed successfully in {elapsed_time:.2f} seconds. Notes saved to {output_file_path}")  
  
    return notes

Read more

[책]Reshuffle: Who wins when AI restacks the knowledge economy

[책]Reshuffle: Who wins when AI restacks the knowledge economy

원래는 Amazon에 가서 Personal Knowledge Managment에 관한 책을 사려고 했다. Sketch Your Mind라는 책이었는데, 그 때 이 책 “Reshuffle”을 발견하였다. AI가 어떻게 Knowledge Economy를 흔들 것가? 라는 부제를 훑어보면서 저자가 쓴 다른 책을 보게 되었는데 거기에 내가 좋아했던 책을쓴 저자라는 것을 알게 되었다. 그래서 크게 고민하지 않고 구매를 하고

By Bongho, Lee
[책]올라운드투자, 누군가의 투자일기

[책]올라운드투자, 누군가의 투자일기

“올라운드 투자”라는 제목을 보았을 때는, “올라운드 플레이어”가 생각이 났다. “올라운드”라는 표현을 오랜만에 들어본 까닭이었다. 그럼에도 불구하고 이 책을 고른 것은 저자가 그간 보여준 컨텐츠에 대한 신뢰가 있던 까닭이었다. 컨텐츠를 다양하게 보는 편이지만 깊이가 아주 있지는 않았다. 여기서 깊이라 함은 기존 전문적인 정량적 분석의 내용의 수준을 말하는 것이다.

By Bongho, Lee
내가 놓치고 있던 미래, 먼저 온 미래를 읽고

내가 놓치고 있던 미래, 먼저 온 미래를 읽고

장강명 작가의 책은, 유학시절 읽고 처음이었다. 유학시절 "한국이 싫어서"라는 책은 동기부여가 상당히 되는 책이었다. 한국을 떠나 새로운 정채성을 학생으로서 Build up 해나가고 있던 상황에서 이 책은 제목부터 꽤 솔깃하였다. 물론 결말이 기억날 정도로 인상깊은 책은 아니었지만 말이다. 그렇게 시간이 흘러 장강명 작가의 책은 더 이상 읽지 않던

By Bongho, Lee