Repository navigation
Expand file tree
/
Copy pathstdlibEx.py
More file actions
81 lines (63 loc) · 3.14 KB
/
Copy pathstdlibEx.py
File metadata and controls
81 lines (63 loc) · 3.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# 표준 라이브러리 : 설치 없이 바로 쓰는 파이썬 기본 도구들
# "이미 누가 만들어 두지 않았을까?" 를 먼저 생각하는 습관이 중요합니다
print('========== datetime : 날짜와 시간 ==========')
from datetime import datetime, date, timedelta
now = datetime(2019, 10, 19, 14, 30, 0) # 결과를 고정하려고 값을 직접 줌
print('그대로 :', now)
print('포맷 :', now.strftime('%Y-%m-%d %H:%M:%S'))
print('한글 포맷 :', now.strftime('%Y년 %m월 %d일'))
print('문자열→날짜:', datetime.strptime('2019-10-19', '%Y-%m-%d'))
d1 = date(2019, 10, 19)
d2 = date(2026, 8, 11)
print('날짜 차이 :', (d2 - d1).days, '일')
print('100일 후 :', d1 + timedelta(days=100))
# 실제 현재 시각은 datetime.now() 로 얻습니다.
print('\n========== collections : 편리한 자료구조 ==========')
from collections import Counter, defaultdict
words = 'the quick brown fox the lazy dog the fox'.split()
print('Counter :', Counter(words))
print('상위 2개 :', Counter(words).most_common(2))
# step05 에서 손으로 짰던 개수 세기를 한 줄로 대신합니다
by_len = defaultdict(list) # 없는 키를 꺼내면 자동으로 빈 리스트를 만든다
for w in words:
by_len[len(w)].append(w)
print('defaultdict:', dict(by_len))
# step08 의 setdefault 를 대신합니다
print('\n========== statistics : 기초 통계 ==========')
import statistics
scores = [85, 73, 68, 90, 88, 95, 55, 62]
print('평균 :', round(statistics.mean(scores), 2))
print('중앙값 :', statistics.median(scores))
print('표준편차:', round(statistics.stdev(scores), 2))
# numpy 없이도 기본 통계는 여기서 됩니다
print('\n========== json : 데이터 주고받기의 표준 ==========')
import json
data = {'이름': '홍길동', '점수': [85, 73, 68], '합격': True}
text = json.dumps(data, ensure_ascii=False) # 객체 → 문자열
print('dumps :', text)
print('보기 좋게:')
print(json.dumps(data, ensure_ascii=False, indent=2))
back = json.loads(text) # 문자열 → 객체
print('loads :', back['이름'], back['점수'])
# ensure_ascii=False 를 안 주면 한글이 \uXXXX 로 나옵니다
print('\n========== pathlib : 경로 다루기 ==========')
from pathlib import Path
p = Path('step08_file') / 'data' / 'scores.csv' # / 로 이어 붙인다
print('경로 :', p)
print('파일명 :', p.name)
print('확장자 :', p.suffix)
print('부모 :', p.parent)
# os.path.join(...) 보다 읽기 쉬워 요즘은 pathlib 을 씁니다
print('\n========== os / sys ==========')
import os, sys
print('현재 폴더 :', os.path.basename(os.getcwd()))
print('파이썬 버전:', sys.version.split()[0])
print('\n========== 그 밖에 알아 두면 좋은 것 ==========')
# math 수학 함수 (sqrt, ceil, floor, pi)
# random 난수 (step03 에서 사용)
# csv CSV 읽기·쓰기 (step08 에서 사용)
# re 정규표현식
# itertools 반복 도구 (조합, 순열, 누적)
import math, itertools
print('math.sqrt(16) :', math.sqrt(16))
print('itertools 조합 :', list(itertools.combinations([1, 2, 3], 2)))