Python - 15. 실전 프로젝트
2025. 1. 20. 01:50ㆍ프로그래밍 언어/Python
Python은 다양한 분야에서 활용 가능한 다재다능한 언어입니다. 이번 섹션에서는 Python으로 수행할 수 있는 실전 프로젝트를 다루며, 각 프로젝트에서 사용하는 핵심 기술과 도구를 살펴봅니다.
15.1 웹 스크래핑
목표
웹에서 데이터를 자동으로 수집하여 분석하거나 저장합니다.
사용 도구
- requests: HTTP 요청 처리
- BeautifulSoup: HTML 파싱
- selenium: 동적 웹 페이지 스크래핑
구현 예제: BeautifulSoup을 활용한 웹 스크래핑
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 특정 데이터 추출
titles = soup.find_all("h1")
for title in titles:
print(title.text)
에러 처리 및 재시도
import requests
from requests.exceptions import RequestException
import time
url = "https://example.com"
for _ in range(3): # 최대 3번 재시도
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
break
except RequestException as e:
print(f"Error: {e}, retrying...")
time.sleep(2)
데이터 저장 방법
import csv
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Title", "Link"])
writer.writerow(["Example", "https://example.com"])
웹사이트 정책 준수
- robots.txt 파일 확인
- 과도한 요청 방지 (적절한 time.sleep 사용)
- 웹사이트 소유자의 허가 필요 시 요청
15.2 자동화 스크립트
목표
반복적이고 시간이 많이 소요되는 작업을 자동화하여 효율성을 높입니다.
사용 도구
- os: 파일 및 디렉터리 관리
- shutil: 파일 복사 및 이동
- schedule: 작업 스케줄링
구현 예제: 파일 정리 자동화
import os
import shutil
import logging
# 로깅 설정
logging.basicConfig(level=logging.INFO, filename="file_organizer.log")
source_folder = "./downloads"
destination_folder = "./organized"
for filename in os.listdir(source_folder):
if filename.endswith(".jpg"):
target_dir = os.path.join(destination_folder, "images")
os.makedirs(target_dir, exist_ok=True)
shutil.move(os.path.join(source_folder, filename), target_dir)
logging.info(f"Moved {filename} to {target_dir}")
elif filename.endswith(".txt"):
target_dir = os.path.join(destination_folder, "documents")
os.makedirs(target_dir, exist_ok=True)
shutil.move(os.path.join(source_folder, filename), target_dir)
logging.info(f"Moved {filename} to {target_dir}")
설정 파일 사용
import configparser
config = configparser.ConfigParser()
config.read("config.ini")
source_folder = config["Paths"]["source_folder"]
에러 알림 기능
import smtplib
from email.message import EmailMessage
def send_error_email(error_message):
msg = EmailMessage()
msg.set_content(error_message)
msg["Subject"] = "Automation Script Error"
msg["From"] = "your_email@example.com"
msg["To"] = "admin@example.com"
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login("your_email@example.com", "password")
server.send_message(msg)
send_error_email("An error occurred in the script.")
15.3 데이터 분석
목표
데이터를 수집, 처리, 시각화하여 의미 있는 인사이트를 도출합니다.
사용 도구
- pandas: 데이터 처리 및 분석
- matplotlib, seaborn: 데이터 시각화
- numpy: 수학 연산 및 배열 처리
데이터 전처리 과정
import pandas as pd
# 데이터 로드
data = pd.read_csv("sales_data.csv")
# 결측치 처리
data.fillna(0, inplace=True)
# 데이터 정렬
data.sort_values("month", inplace=True)
고급 시각화 예제
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
data = pd.DataFrame({"month": ["Jan", "Feb", "Mar"], "sales": [200, 300, 250]})
sns.barplot(x="month", y="sales", data=data)
plt.title("Monthly Sales")
plt.show()
통계 분석 추가
from scipy.stats import ttest_ind
# 두 그룹 간 평균 비교
group_a = [20, 30, 25, 35]
group_b = [22, 28, 24, 33]
stat, p_value = ttest_ind(group_a, group_b)
print(f"t-statistic: {stat}, p-value: {p_value}")
15.4 게임 제작
목표
Python의 게임 라이브러리를 활용하여 간단한 게임을 개발합니다.
사용 도구
- pygame: 2D 게임 개발
구현 예제: 간단한 게임 제작
import pygame
import sys
pygame.init()
# 화면 설정
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Simple Game")
# 색상 정의
white = (255, 255, 255)
blue = (0, 0, 255)
# 게임 루프
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(white)
pygame.draw.circle(screen, blue, (200, 150), 30)
pygame.display.flip()
15.5 웹 애플리케이션 개발
목표
웹 프레임워크를 사용하여 웹 애플리케이션을 개발합니다.
사용 도구
- Flask: 가벼운 웹 프레임워크
- Django: 강력한 웹 프레임워크
구현 예제: Flask를 활용한 간단한 웹 애플리케이션
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"
if __name__ == "__main__":
app.run(debug=True)
프로젝트 구조와 의존성 관리
프로젝트 디렉터리 구조 예제
project_name/
|-- data/
| |-- raw_data.csv
|-- src/
| |-- main.py
|-- config/
| |-- config.ini
|-- requirements.txt
의존성 관리
- 프로젝트의 의존성을 requirements.txt에 기록합니다.
requests
beautifulsoup4
pandas
matplotlib
배포 방법
- 패키징: setuptools 또는 pyinstaller 활용
- Docker 컨테이너화: 애플리케이션 배포를 간소화
- 클라우드 배포: AWS, GCP, Azure를 활용한 배포
Python은 웹 스크래핑, 자동화 스크립트, 데이터 분석, 게임 제작, 웹 애플리케이션 개발 등 다양한 프로젝트에 활용될 수 있습니다. 각 분야의 도구와 기법을 잘 활용하여 효과적인 프로젝트를 완성할 수 있습니다.
'프로그래밍 언어 > Python' 카테고리의 다른 글
Python Tkinter - 4. 메뉴, 다이얼로그, 스타일링 (0) | 2025.02.03 |
---|---|
Python Tkinter - 3. 고급 위젯과 데이터 관리 (0) | 2025.02.03 |
Python - 14. 보안과 암호화 (0) | 2025.01.20 |
Python - 13. 코드 품질과 테스팅 (0) | 2025.01.20 |
Python Tkinter - 2. 레이아웃 관리와 고급 이벤트 처리 (0) | 2025.01.20 |