데이터를 효율적으로 모으고 활용하기 위해 중요한 단계
| 방법 | 설명 |
|---|---|
| 웹 스크래핑(Web Scraping, 웹 크롤링) | 웹사이트에서 HTML 데이터를 가져와 필요한 정보 추출 |
| API 활용 | REST API를 통해 JSON 형태의 데이터 제공 |
| 데이터베이스에서 데이터 가져오기 | 이미 수집된 데이터를 데이터베이스에서 쿼리를 통해 추출 |
| 공개된 데이터셋 활용 | 정부/기업/연구기관에서 제공하는 공개 데이터셋 다운하거나 API를 통해 사용 |
| IoT 또는 센서 데이터 수집 | 센서를 이용해 실시간 데이터 수집 (온도 센서, 카메라, GPS 장치 등) |
| 소셜 미디어 데이터 수집 | 소셜 미디어 플랫폼에서 사용자 활동 데이터 수집 (해당 플랫폼 API 사용) |
pip install requests
import requests
url = 'https://jsonplaceholder.typicode.com/posts'
response = requests.get(url) # GET method: 서버에서 데이터 가져옴
if response.status_code == 200:
# 1_response.text: 응답을 문자열로 반환
print(response.text[:500])
# 2_response.json(): JSON 형식의 응답 -> 딕셔너리로 변환
data = response.json()
print(data['title'])
print(data['body'])
else:
print(f'오류 발생: {response.status_code}') # HTTP 상태 코드 반환
import requests
url = 'https://jsonplaceholder.typicode.com/posts'
params = {'userId': 1}
response = requests.get(url, params=params)
if response.status_code == 200:
print(response.json())
else:
print(f'오류 발생: {response.status_code}') # HTTP 상태 코드 반환
웹 페이지의 구조를 정의하는 마크업 언어
<태그명 속성="값"> 내용 </태그명>
<html> | html
<body> | └── body
<h1>title</h1> | ├── h1
<p>content</p> | │ └── "Hello, World!"
</body> | └── p
</html> | └── "This is a paragraph."
Python에서 HTML과 XML 문서를 파싱하고, 원하는 데이터를 추출할 때 사용하는 라이브러리
pip install beautifulsoup4
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>Example Page</title>
</head>
<body>
<h1>Welcome to Web Scraping</h1>
<p class="description">This is an example paragraph.</p>
<a href="https://example.com1">Visit Example1</a>
<a href="https://example.com2">Visit Example2</a>
<a href="https://example.com3">Visit Example3</a>
<a href="https://example.com4">Visit Example4</a>
</body>
</html>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.title.string)
print(soup.h1.string)
print(soup.a['href'])
# 모든 <a> 태그 찾기
links = soup.find_all('a')
# 클래스가 "description"인 태그 찾기
description = soup.select_one('.description')
웹 브라우저를 자동으로 제어할 수 있게 해주는 라이브러리
pip install selenium
REST 원칙을 따르는 API
https://www.example/resource/{id}| 메서드 | 동작 |
|---|---|
| GET | 데이터 조회 |
| POST | 새 데이터 생성 |
| PUT | 기존 데이터 수정 |
| DELETE | 데이터 삭제 |
POST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer token123
{
"name": "hong",
"email": "123@example.com"
}
대량 데이터 저장, 분석 초기 단계에 적합
import csv
data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
# CSV 파일로 저장
with open('data.csv', mode='w', encoding='utf-8', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
data = pd.read_csv('data.csv') # CSV 파일 -> 데이터프레임 형태로 변환
데이터 요약, 보고서 작성, 분석 작업에 유용
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [30, 25, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
df.to_excel('data.xlsx', index=False) # Excel 파일로 저장
data = pd.read_excel('data.xlsx') # Excel 파일 읽기
웹이나 모바일 애플리케이션과의 데이터 교환에 적합
import json
data = {
'people': [
{'name': 'Alice', 'age': 30, 'city': 'New York'},
{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
{'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
]
}
with open('data.json', mode='w', encoding='utf-8') as file:
json.dump(data, file, indent=4) # json.dump(): JSON형식으로 저장
with open('data.json', mode='r') as file:
data2 = json.load(file) # JSON 파일 -> 딕셔너리로 변환: json.load()
파일 기반의 관계형 데이터베이스 관리 시스템(RDBMS)
import sqlite3
# 데이터베이스 연결 (파일 생성)
connection = sqlite3.connect('example.db')
# 연결 종료
connection.close()
connection = sqlite3.connect('example.db')
cursor = connection.cursor()
# CREATE TABLE IF NOT EXISTS: 테이블이 없을 경우에만 생성
# PRIMARY KEY AUTOINCREMENT: 기본 키, 자동 증가 값 사용
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER
)
""")
connection.close()
cursor.execute("INSERT INTO users (name, age, city)
VALUES (?, ?, ?)", # ?: 자리표시자, SQL 인젝션 방지
("Alice", 30, "New York"))
# 여러 데이터 삽입
data = [
("Bob", 25, "Los Angeles"),
("Charlie", 35, "Chicago"),
("Diana", 28, "Houston")
]
cursor.executemany("INSERT INTO users (name, age, city)
VALUES (?, ?, ?)", data)
connection.commit() # 변경사항 저장
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall() # fetchall(): 모든 조회 결과 가져옴
# fetchone(): 한 행씩 가져옴
cursor.execute("UPDATE users SET age = ? WHERE
name = ?", (31, "Alice"))
connection.commit()
cursor.execute("DELETE FROM users WHERE name = ?",
("Bob",))
connection.commit()
데이터를 시각화하기 위한 가장 기본적인 라이브러리
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y, marker='o', linestyle='-', color='b', label='Prime Numbers')
plt.title("Line Plot Example")
plt.show()
import matplotlib.pyplot as plt
categories = ['A', 'B', 'C', 'D', 'E']
values = [5, 7, 3, 8, 4]
# 막대 그래프 생성
plt.bar(categories, values, color='skyblue', edgecolor='black’)
# 수평 막대 그래프 생성
plt.barh(categories, values, color='lightgreen', edgecolor='black')
plt.title("Bar Chart Example")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(1000)
# 히스토그램 생성
plt.hist(data, bins=20, color='orange',edgecolor='black', alpha=0.7)
plt.title("Histogram Example")
plt.show()
데이터 시각화를 위해 설계, 복잡한 데이터를 쉽게 이해할 수 있도록 함
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
mask = np.triu(np.ones_like(data, dtype=bool))
sns.heatmap(data, annot=True, mask=mask,cmap='coolwarm')
plt.title("Heatmap Example")
plt.show()
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", data=tips, palette="Set2")
plt.title("BoxPlot Example")
plt.show()
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
sns.violinplot(x="day", y="total_bill", data=tips, palette="muted", split=True)
plt.title("ViolinPlot Example")
plt.show()