Ch.2 Python 첫걸음 — 데이터를 다루다

종합 실습 — 미니 데이터 파이프라인

학습한 문법을 조합하여 실제 프로그램을 작성한다데이터 파이프라인의 4단계 처리를 구현한다

지금까지 배운 문법으로 진짜 프로그램을 만들어보자

변수, 조건문, 반복문, 함수, 클래스 — 모든 것을 하나의 프로그램으로 합쳐봅시다.

각각은 알겠는데, 합치면 어떻게 되지?

따라치기 실습 — 완성된 코드를 보고 자기 것으로 만드는 시간입니다.


article

핵심 내용

변수 → 타입 → 문자열 → 조건문 → 반복문 → JSON → 함수 → 에러 처리 → 클래스. 이 조각들을 모으면 데이터 전처리기가 됩니다. 실제 AI 학습의 첫 단계인 데이터 파이프라인을 직접 만들어봅시다. 이것이 ChatGPT의 학습 데이터가 거치는 과정과 본질적으로 같습니다.

4단계로 데이터를 처리합니다

1. 정제: 공백·줄바꿈 정리

2. 필터: 품질 미달 제거

3. 중복제거: 같은 텍스트 제거

4. 통계: 토큰 수·빈도 분석

4단계를 하나의 클래스로 통합해봅시다

# [따라치기] 전체 파이프라인 클래스
from collections import Counter

class DataPipeline:
    def __init__(self):
        self.data = []

    def load(self, texts):
        self.data = texts
        print(f"📥 {len(texts)}개 로드")

    def clean(self):
        cleaned = []
        for t in self.data:
            t = t.strip()
            while "  " in t:
                t = t.replace("  ", " ")
            cleaned.append(t)
        self.data = cleaned
        print("🧹 정제 완료")

    def filter_quality(self, min_len=5):
        before = len(self.data)
        self.data = [t for t in self.data
                     if len(t) >= min_len
                     and sum(c.isalpha() or c == " "
                             for c in t) / max(len(t),1) >= 0.5]
        print(f"🔍 필터: {before}→{len(self.data)}개")

    def deduplicate(self):
        before = len(self.data)
        seen = set()
        unique = []
        for t in self.data:
            if t not in seen:
                seen.add(t)
                unique.append(t)
        self.data = unique
        print(f"🔄 중복제거: {before}→{len(self.data)}개")

    def analyze(self):
        tokens = []
        for t in self.data:
            tokens.extend(t.split())
        freq = Counter(tokens)
        print(f"📊 토큰 {len(tokens)}개, 고유 {len(freq)}개")
        for w, c in freq.most_common(3):
            print(f"   {w}: {c}")

    def run(self):
        self.clean()
        self.filter_quality()
        self.deduplicate()
        self.analyze()

# 실행!
pipe = DataPipeline()
pipe.load([
    "  Python은  AI에  사용된다  ",
    "", "!@#", "x",
    "딥러닝은 신경망이다",
    "Python은 AI에 사용된다",
    "GPU로 AI를 학습한다",
    "Transformer가 핵심이다",
])
pipe.run()

[x*2 for x in data if x > 3] 에서 if x > 3의 역할은?

Counter는 어떤 기능을 제공하는가?

종합 실습 완료!

edit_note

정리 노트

종합 실습 — 미니 데이터 파이프라인

파이프라인 4단계

① 정제(clean)
공백·줄바꿈 정리 — strip(), replace()
② 필터(filter)
품질 미달 데이터 제거 — len(), 조건문 활용
③ 중복제거(dedup)
set()으로 이미 본 텍스트 추적, 중복 스킵
④ 통계(analyze)
Counter로 토큰 빈도 분석, most_common()

Ch2 문법 총정리

변수·타입·f-string
데이터를 담고, 구별하고, 출력하는 기초
if/for + 함수
데이터를 필터링·반복·재사용하는 도구
클래스 + 에러처리
코드를 조직화하고 안전하게 실행

이 4단계가 실제 ChatGPT 학습 데이터가 거치는 전처리 과정과 본질적으로 동일!

image

시각 자료

다이어그램: py-scene-data-pipeline
check_circle

핵심 정리

  • 1변수·타입·f-string → 데이터 기초
  • 2if/for + 함수 + 에러처리 → 데이터 필터링
  • 3클래스 → 코드 조직화

퀴즈와 인터랙션으로 더 깊이 학습하세요

play_circle인터랙티브 레슨 시작