SlideShare ist ein Scribd-Unternehmen logo
1 von 67
파이썬 표준 라이브러리
정보기술 시대에 유익한 파이썬 프로그래밍 – 제 7 강
동양미래대학교
2015.7
최용 <sk8er.choi@gmail.com>
강의 주제
• Python 표준 라이브러리 일부 소개
• 텍스트 프로세싱: 문자열 포매팅
• 데이터 타입: datetime, calendar, collections, copy
• 숫자 및 수학 모듈: math, random
• 함수형 프로그래밍
• map(), filter() 내장 함수
• functools, itertools 모듈
• 파일 및 디렉터리 접근: os.path, pathlib, fnmatch
• 데이터 영속성: pickle
• 파일 포맷: csv
• 운영체제 일반 서비스: os
• 파이썬 런타임: sys
• 개발 도구: unittest, doctest
• 데이터베이스, 인터넷 관련 모듈은 9강에서 다룸 더그 헬먼 저, 정승원 역,<The Python
Standard Library by Example>
문자열 포매팅
Advanced String Formatting
Advanced String Formatting
• ‘%’ 연산자의 제약을 극복하기 위한 새로운 포매팅 방법
• 문자열 메소드 format() 또는 내장 함수 format()
• Format Specification Mini-Language
Advanced String Formatting
– positional argument, keyword argument
>>> '조{0}모{1}'.format('삼', '사') # positional argument
'조삼모사'
>>> '조{a}모{b}'.format(a='삼', b='사') # keyword argument
'조삼모사'
>>> '조{}모{}'.format('삼', '사') # 생략(묵시적으로 위치 지정)
'조삼모사'
>>> '{0}{1}{2}{3}{4}{5}{6}'.format('빨', '주', '노', '초', '파', '남', '보')
'빨주노초파남보'
>>> '{6}{5}{4}{3}{2}{1}{0}'.format('빨', '주', '노', '초', '파', '남', '보')
'보남파초노주빨'
Advanced String Formatting
– width, alignment
>>> '조{:2}모{:2}'.format('삼', '사') # 폭(width) 2
'조삼 모사 '
>>> for n in (1, 23, 456):
... print('{:>4}'.format(n)) # 오른쪽 정렬, 폭 4
...
1
23
456
>>> for fruit in ('apple', 'banana', 'strawberry'):
... print('{:^10}'.format(fruit)) # 가운데 정렬, 폭 10
...
apple
banana
strawberry
Advanced String Formatting
– presentation types
>>> '{:s}등'.format('일') # 's': 문자열(string)
'일등'
>>> '{:d}등'.format(1) # 'd': 십진수(decimal)
'1등'
>>> '{:2.1f}도'.format(36.55) # 'f': 고정소수점(fixed point)
'36.5도'
>>> '{:2.1e}도'.format(36.55) # 'e': 지수 표기(exponent notation)
'3.7e+01도'
Advanced String Formatting
– presentation types
>>> fmt = '{:.2%} {:s} 외에는 아무 것도 넣지 않았습니다.' # '%': 백분율
>>> for n in [0.99, 0.999, 0.9999, 0.99999]:
... print(fmt.format(n, '꿀'))
...
99.00% 꿀 외에는 아무 것도 넣지 않았습니다.
99.90% 꿀 외에는 아무 것도 넣지 않았습니다.
99.99% 꿀 외에는 아무 것도 넣지 않았습니다.
100.00% 꿀 외에는 아무 것도 넣지 않았습니다.
Advanced String Formatting
– type conversion
>>> '{:s}등'.format(1) # int에 대해서 포맷 's' 사용 못함
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 's' for object of type 'int'
>>> '{!r:}등'.format(1) # repr()을 사용하여 문자열로 변환
'1등'
>>> '{!s:}등'.format(1) # str()을 사용하여 문자열로 변환
'1등'
정규 표현식
Regular Expression
re
• 텍스트 패턴 매칭을 위한 강력한 도구
• https://developers.google.com/edu/python/regular-expressions
>>> import re
>>> s = 'an example word:cat!!'
>>> m = re.search(r'word:www', s)
>>> if m:
... print('found', m.group())
... else:
... print('did not find')
...
found word:cat
>>> print('1n2n3')
1
2
3
>>> print(r'1n2n3')
1n2n3
re – 기본 패턴
>>> re.search(r'iii', 'piiig')
<_sre.SRE_Match object; span=(1, 4), match='iii'>
>>> re.search(r'igs', 'piiig') # match=None
>>> re.search(r'..g', 'piiig') # . -- any single char
<_sre.SRE_Match object; span=(2, 5), match='iig'>
>>> re.search(r'ddd', 'p123g') # d -- [0-9]
<_sre.SRE_Match object; span=(1, 4), match='123'>
>>> re.search(r'www', '@@abcd!!') # w -- [a-zA-Z0-9_]
<_sre.SRE_Match object; span=(2, 5), match='abc'>
>>> re.search(r'^...', 'p123g') # ^ -- start
<_sre.SRE_Match object; span=(0, 3), match='p12'>
>>> re.search(r'...$', 'p123g') # $ -- end
<_sre.SRE_Match object; span=(2, 5), match='23g'>
re – Repitation (반복)
• + -- 1회 이상 나타남(occurrences)
• * -- 0회 이상
• ? -- 0 또는 1회
>>> re.search(r'er+y', 'strawberry')
<_sre.SRE_Match object; span=(6, 10), match='erry'>
>>> re.search(r'e+y', 'strawberry')
>>> re.search(r'e*y', 'strawberry')
<_sre.SRE_Match object; span=(9, 10), match='y'>
>>> re.search(r'er?y', 'strawberry')
>>> re.search(r'ex?.+y', 'strawberry')
<_sre.SRE_Match object; span=(6, 10), match='erry'>
re – 그룹 추출
>>> s = 'purple alice-b@google.com monkey dishwasher'
>>> m = re.search('([w.-]+)@([w.-]+)', s)
>>> if m:
... print(m.group())
... print(m.group(1))
... print(m.group(2))
...
alice-b@google.com
alice-b
google.com
re – findall
>>> s = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher'
>>> emails = re.findall(r'[w.-]+@[w.-]+', s)
>>> for email in emails:
... print(email)
...
alice@google.com
bob@abc.com
데이터 타입
Data Types
datetime
• 날짜, 시간에 관련된 기능
>>> from datetime import datetime
>>> datetime.now().weekday() # 0: 월요일, 6: 일요일
3
>>> datetime.now().isoweekday() # 1: 월요일, 7: 일요일
4
>>> tw = todays_weekday = datetime.now().isoweekday()
>>> if 1 <= tw <= 5:
... print('차량번호 끝자리가 %d 또는 %d인 차량은 주차금지' % (tw, tw + 5))
... else:
... print('주말은 차량 5부제를 시행하지 않습니다')
...
calendar
>>> import calendar
>>> calendar.prmonth(2015, 7)
July 2015
Mo Tu We Th Fr Sa Su
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
>>> calendar.setfirstweekday(6)
>>> calendar.prmonth(2015, 7)
July 2015
Su Mo Tu We Th Fr Sa
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
>>> calendar.isleap(2014)
False
>>> calendar.isleap(2016)
True
6: Sunday
collections
collections
• Python의 일반 목적 내장 자료형(dict, list, set, tuple)을
대체하는 특수한 컨테이너 자료형
https://docs.python.org/3/library/collections.html
collections.ChainMap
>>> from collections import ChainMap
>>> default_settings = {'a': 1, 'b': 2}
>>> custom_settings = {'b': 10, 'c': 11}
>>> applied_settings = ChainMap(custom_settings, default_settings)
>>> applied_settings
ChainMap({'b': 10, 'c': 11}, {'b': 2, 'a': 1})
>>> for k, v in applied_settings.items():
... print(k, v)
...
b 10
c 11
a 1
http://stackoverflow.com/questions/23392976/what-is-the-purpose-of-collections-chainmap
collections.Counter
>>> import collections
>>> C = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
>>> C
Counter({'b': 3, 'a': 2, 'c': 1})
>>> C.update('abcdaab')
>>> C
Counter({'b': 5, 'a': 5, 'c': 2, 'd': 1})
collections.deque – double-ended queue
>>> import collections
>>> d = collections.deque([1, 2],
maxlen=5)
>>> d.append(3)
>>> d
deque([1, 2, 3], maxlen=5)
>>> d.appendleft(4)
>>> d
deque([4, 1, 2, 3], maxlen=5)
>>> d.append(5)
>>> d
deque([4, 1, 2, 3, 5], maxlen=5)
>>> d.append(6)
>>> d
deque([1, 2, 3, 5, 6], maxlen=5)
>>> d.pop()
6
>>> d
deque([1, 2, 3, 5], maxlen=5)
>>> d.popleft()
1
>>> d
deque([2, 3, 5], maxlen=5)
>>> d.extend([7, 8])
>>> d
deque([2, 3, 5, 7, 8], maxlen=5)
>>> list(d)
[2, 3, 5, 7, 8]
collections.defaultdict
>>> import collections
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = collections.defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d
defaultdict(<class 'list'>, {'red': [1], 'yellow': [1, 3], 'blue': [2, 4]})
>>> list(d.items())
[('red', [1]), ('yellow', [1, 3]), ('blue', [2, 4])]
https://docs.python.org/3/library/collections.html#defaultdict-examples
collections.namedtuple
>>> import collections
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)
>>> print(p[0], p[1]) # indexable like plain tuple
11 22
>>> print(p.x, p.y) # field accessible by name
11 22
>>> p # readable __repr__
Point(x=11, y=22)
https://docs.python.org/3/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields
collections.OrderedDict
>>> d = {}
>>> d['a'] = 'A'
>>> d['b'] = 'B'
>>> d['c'] = 'C'
>>> d['d'] = 'D'
>>> d['e'] = 'E'
>>> d
{'d': 'D', 'b': 'B', 'c': 'C', 'a':
'A', 'e': 'E'}
>>> import collections
>>> od = collections.OrderedDict()
>>> od['x'] = 'X'
>>> od['y'] = 'Y'
>>> od['a'] = 'A'
>>> od['b'] = 'B'
>>> od['c'] = 'C'
>>> od
OrderedDict([('x', 'X'), ('y', 'Y'),
('a', 'A'), ('b', 'B'), ('c', 'C')])
collections – UserDict, UserList, UserString
• dict, list, string을 직접 상속할 수 없었을 때에 사용한 wrapper
• 현재는 dict, list, str을 바로 상속할 수 있으므로 필요성이 낮음
collections.abc
>>> from abc import *
>>> class C(metaclass=ABCMeta):
... @abstractmethod
... def absMethod(self):
... pass
...
>>> c = C()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract
class C with abstract methods absMethod
>>> class B(C):
... def absMethod(self):
... print("Now a concrete method")
...
>>> b = B()
>>> b.absMethod()
Now a concrete method
http://autonomist.tistory.com/entry/펌-Python-3-입문-Part-2-고급-주제
copy – Shallow and Deep Copy
얕은 복사(shallow copy)
>>> L1 = [['apple', 'banana'], 'milk']
>>> import copy
>>> L2 = copy.copy(L1)
>>> L1[0].append('orange')
>>> L1[1] = 'cheese'
>>> L1
[['apple', 'banana', 'orange'], 'cheese']
>>> L2
[['apple', 'banana', 'orange'], 'milk']
깊은 복사(deep copy)
>>> L1 = [['apple', 'banana'], 'milk']
>>> import copy
>>> L2 = copy.deepcopy(L1)
>>> L1[0].append('orange')
>>> L1[1] = 'cheese'
>>> L1
[['apple', 'banana', 'orange'], 'cheese']
>>> L2
[['apple', 'banana'], 'milk']
숫자 및 수학 모듈
Numeric and Mathematical Modules
math
>>> math.pi # 원주율 값
3.141592653589793
>>> math.pow(2, 5) # 2 * 2 * 2 * 2 * 2
32.0
>>> math.sqrt(144) # 144의 제곱근
12.0
>>> math.factorial(4) # 1 * 2 * 3 * 4
24
random 모듈
• Pseudo random number generator
• Uniform selection
• 보안 목적으로는 사용 금지
os.urandom() 또는 SystemRandom 사용
• https://docs.python.org/3.4/library/random.html 참조
random.choice()
>>> import random
>>> dice = [i for i in range(1, 7)]
>>> dice
[1, 2, 3, 4, 5, 6]
>>> random.choice(dice)
4
>>> random.choice(dice)
6
>>> random.choice(dice)
2
>>> random.choice(dice)
2
>>> random.choice('aeiou')
'u'
>>> random.choice('aeiou')
'a'
>>> random.choice('aeiou')
'i'
>>> random.choice('aeiou')
'a'
>>> random.choice('aeiou')
'a'
>>> random.choice('aeiou')
'u'
random.randrange()
>>> random.randrange(7)
2
>>> random.randrange(7)
4
>>> random.randrange(7)
0
>>> random.randrange(7)
3
>>> random.randrange(7)
1
>>> random.randrange(7)
1
>>> random.randrange(7)
0
>>> random.randrange(3, 30, 3)
15
>>> random.randrange(3, 30, 3)
24
>>> random.randrange(3, 30, 3)
3
>>> random.randrange(3, 30, 3)
12
>>> random.randrange(3, 30, 3)
27
>>> random.randrange(3, 30, 3)
21
>>> random.randrange(3, 30, 3)
24
random.shuffle()
>>> dice
[1, 2, 3, 4, 5, 6]
>>> random.shuffle(dice)
>>> dice
[5, 2, 4, 3, 1, 6]
>>> new_dice = tuple([i for i in range(1, 7)])
>>> new_dice
(1, 2, 3, 4, 5, 6)
>>> random.shuffle(new_dice)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:Python34librandom.py", line 272, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'tuple' object does not support item assignment
함수형 프로그래밍
Functional Programming in Python
절차적 vs 함수형
명령형(Imperative),
절차적(procedural) 접근
• 계산을 실행하는 순서를 기술
• 반복(Loop)
• 상태(state): 중간 결과 저장
• 상태에 따라 결과가 바뀌는
부작용이 있음.
선언적(declarative),
함수형(functional) 접근
• 무엇을 하려고 하는지를 기술
• 재귀(recursion)
• Loop와 state가 없음
• 상태로 인한 부작용을 배제
map() 내장 함수
• Iterable object의 각 원소에 대하여 함수를 적용
>>> prime_nums = (1, 2, 3, 5, 7, 9, 11, 13)
>>> [p * p for p in prime_nums]
[1, 4, 9, 25, 49, 81, 121, 169]
>>> list(map(lambda x: x * x, prime_nums))
[1, 4, 9, 25, 49, 81, 121, 169]
>>> data = '성 춘향| 010-300-3333 |광한루|'
>>> data.split('|')
['성 춘향', ' 010-300-3333 ', '광한루', '']
>>> list(map(str.strip, data.split('|')))
['성 춘향', '010-300-3333', '광한루', '']
맵: 네모()
filter() 내장 함수
• 원소들을 기준(함수가 True를 반환)에 따라 걸러냄
• filter 타입의 객체를 반환
>>> multiples_of_3 = range(3, 31, 3) # 30 이하의 3의 배수
>>> tuple(multiples_of_3)
(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)
>>> tuple(filter(lambda x: x % 15 != 0, multiples_of_3)) # 그 중 15의 배수가 아닌 것
(3, 6, 9, 12, 18, 21, 24, 27)
>>> langs = ('C', 'Java', 'Perl', 'PHP', 'Python')
>>> tuple(filter(lambda s: s.startswith('P'), langs)) # 'P' 자로 시작하는 언어
('Perl', 'PHP', 'Python')
필터: 파란색이냐()
itertools – count()
>>> import itertools
>>> natural = itertools.count(1)
>>> next(natural)
1
>>> next(natural)
2
>>> next(natural)
3
>>> even = itertools.count(2, 2)
>>> next(even)
2
>>> next(even)
4
>>> next(even)
6
>>> negative = itertools.count(-1, -1)
>>> next(negative)
-1
>>> next(negative)
-2
>>> next(negative)
-3
itertools – cycle()
>>> import itertools
>>> day = itertools.cycle('월화수목금금금')
>>> next(day)
'월'
>>> next(day)
'화'
>>> next(day)
'수'
>>> next(day)
'목'
>>> next(day)
'금'
>>> next(day)
'금'
>>> next(day)
'금'
>>> next(day)
'월'
>>> next(day)
'화'
>>> next(day)
'수'
>>> next(day)
'목'
월
화
수
목금
금
금
functools – reduce() 함수
• 주어진 함수를 이용하여 원소들을 결합
>>> L = [1, 2, 3, 4, 5]
>>> import functools
>>> functools.reduce(lambda a, x: a + x, L)
15
https://docs.python.org/3/library/functools.html 참조
파일과 디렉터리 접근
File and Directory Access
os.path – 일반적인 경로명 조작
>>> import os
>>> print(os.path.join('c:python34', 'python.exe'))
c:python34python.exe
>>> print(os.path.join('/usr/bin', 'python'))
/usr/binpython
>>> print(os.path.expanduser('~'))
C:UsersYong Choi
>>> print(os.path.join(os.path.expanduser('~'), 'documents'))
C:UsersYong Choidocuments
http://juehan.github.io/DiveIntoPython3_Korean_Translation/comprehensions.html#ospath
pathlib – 객체 지향 파일시스템 경로(ver. 3.4)
• Pure Path: 파일 시스템에 실제로 접근하지 않음
• Concrete Path: Pure Path 클래스들의 서브클래스.
Path 객체에 대한 시스템 콜을 위한 메소드를 제공
>>> from pathlib import *
>>> p = Path('c:/python34/python.exe')
>>> p
WindowsPath('c:/python34/python.exe')
>>> p.exists()
True
>>> PurePath('/usr/bin/python3').parts
('', 'usr', 'bin', 'python3')
https://docs.python.org/3/library/pathlib.html
pathlib – properties
>>> PureWindowsPath('c:/Program Files/').drive
'c:'
>>> PurePosixPath('my/library/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
pathlib – methods
>>> PureWindowsPath('c:/Windows').as_uri()
'file:///c:/Windows'
>>> PurePosixPath('/etc').joinpath('passwd')
PurePosixPath('/etc/passwd')
>>> PurePath('/a/b/c.py').match('b/*.py')
True
>>> PurePath('/a/b/c.py').match('a/*.py')
False
>>> PureWindowsPath('b.py').match('*.PY')
True
>>> PurePosixPath('b.py').match('*.PY')
False
fnmatch – 파일명 매칭
>>> import fnmatch
>>> import os
>>> matches = []
>>> for root, dirnames, filenames in os.walk('C:Python34'):
... for filename in fnmatch.filter(filenames, '*.exe'):
... matches.append(os.path.join(root, filename))
...
>>> matches
['C:Python34python.exe', 'C:Python34pythonw.exe', 'C:Python34Libdi
stutilscommandwininst-10.0-amd64.exe', 'C:Python34Libdistutilscomman
dwininst-10.0.exe', 'C:Python34Libdistutilscommandwininst-6.0.exe',
데이터 영속성
Data Persistence
pickle
• Python 개체를 파일에 저장
• 피클
>>> import pickle
>>> favorite_color = {'lion': 'yellow', 'kitty': 'red'}
>>> pickle.dump(favorite_color, open('favorite_color', 'wb'))
• 언피클
>>> import pickle
>>> favorite_color = pickle.load(open('favorite_color', 'rb'))
>>> favorite_color
{'kitty': 'red', 'lion': 'yellow'}
https://wiki.python.org/moin/UsingPickle
https://commons.wikimedia.org/wiki/File:Pickled_Walnuts_Jar.jpg
파일 형식
File Formats
CSV(Comma Seperated Values)
csv.writer
>>> import csv
>>> with open('eggs.csv', 'w', newline='') as csvfile:
... spamwriter = csv.writer(csvfile, delimiter=' ',
... quotechar='|', quoting=csv.QUOTE_MINIMAL)
... spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
... spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
...
40
37
Spam Spam Spam Spam Spam |Baked Beans|
Spam |Lovely Spam| |Wonderful Spam|
csv.reader
Spam Spam Spam Spam Spam |Baked Beans|
Spam |Lovely Spam| |Wonderful Spam|
>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print(', '.join(row))
...
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
https://docs.python.org/3/library/csv.html
운영 체제 일반 서비스
Generic Operating System Services
os
>>> os.environ['HOME']
'C:UsersYong Choi'
>>> os.environ['NUMBER_OF_PROCESSORS']
'4'
>>> os.getcwd()
'C:UsersYong Choi'
>>> os.chdir('Program Files')
>>> os.getcwd()
'C:Program Files'
파이썬 런타임
sys
>>> sys.platform
'win32'
>>> sys.byteorder
'little'
>>> sys.getwindowsversion()
sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service
Pack 1')
>>> sys.version_info
sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0)
>>> sys.winver
'3.4'
sys.argv
• sys_argv_test.py
import sys
for i in range(len(sys.argv)):
print('sys.argv[{:d}]: {:s}'.format(i, sys.argv[i]))
> py -3 sys_argv_test.py a b c d
sys.argv[0]: sys_argv_test.py
sys.argv[1]: a
sys.argv[2]: b
sys.argv[3]: c
sys.argv[4]: d
sys.path
• D:summer_pythonlecture07mycalendar.py
import calendar
def prmonth(theyear, themonth, w=0, l=0):
calendar.setfirstweekday(6)
calendar.prmonth(theyear, themonth, w, l)
>>> import sys
>>> sys.path.append('D:summer_pythonlecture07')
>>> import mycalendar
>>> mycalendar.prmonth(2015, 7)
개발도구
Development Tools
unittest
• test fixture: 테스트를 수행하기 위한 준비와 뒷정리
• test case: 테스트의 개별 단위
• test suite: 함께 수행할 테스트들을 묶은 것
• test runner: 테스트의 수행 및 그 결과를 사용자에게 보여주는
것까지
unittest - assertEqual
import unittest
def fun(x):
return x + 1
class MyTest(unittest.TestCase):
def test(self):
self.assertEqual(fun(3), 4)
if __name__ == '__main__':
unittest.main()
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
http://docs.python-guide.org/en/latest/writing/tests/
unittest – failUnless, failIf
import unittest
def IsOdd(n):
return n % 2 == 1
class IsOddTests(unittest.TestCase):
def testOne(self):
self.failUnless(IsOdd(1))
def testTwo(self):
self.failIf(IsOdd(2))
if __name__== '__main__':
unittest.main()
..
-------------------------------------------
Ran 2 tests in 0.000s
OK
http://www.openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html
unittest – assertRaises
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
https://docs.python.org/3.4/library/unittest.html#basic-example
doctest
def square(x):
"""Squares x.
>>> square(2)
4
>>> square(-3)
9
"""
return x + x
if __name__ == '__main__':
import doctest
doctest.testmod()
> python mysquare.py
*******************************************
File "mysquare.py", line 6, in __main__.square
Failed example:
square(-3)
Expected:
9
Got:
-6
*******************************************
1 items had failures:
1 of 2 in __main__.square
***Test Failed*** 1 failures.
2to3
• Python 2로 작성된 스크립트를 Python 3로 자동 변환
> dir /b
hello.py
> type hello.py
print 'Hello'
> 2to3 -w hello.py
> dir /b
hello.py.bak
hello.py
> type hello.py
print('Hello')
print 'Hello' print('Hello')2to3

Weitere ähnliche Inhalte

Was ist angesagt?

CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
Codecamp Romania
 

Was ist angesagt? (20)

Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, future
 
Python basic
Python basic Python basic
Python basic
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
엘라스틱서치 적합성 이해하기 20160630
엘라스틱서치 적합성 이해하기 20160630엘라스틱서치 적합성 이해하기 20160630
엘라스틱서치 적합성 이해하기 20160630
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 

Ähnlich wie Python 표준 라이브러리

Functions in python
Functions in pythonFunctions in python
Functions in python
Ilian Iliev
 

Ähnlich wie Python 표준 라이브러리 (20)

An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
 
Py3k
Py3kPy3k
Py3k
 
Python Training v2
Python Training v2Python Training v2
Python Training v2
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
30 分鐘學會實作 Python Feature Selection
30 分鐘學會實作 Python Feature Selection30 分鐘學會實作 Python Feature Selection
30 分鐘學會實作 Python Feature Selection
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
30 分鐘學會實作 Python Feature Selection
30 分鐘學會實作 Python Feature Selection30 分鐘學會實作 Python Feature Selection
30 分鐘學會實作 Python Feature Selection
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.ppt
 
Python na Infraestrutura 
MySQL do Facebook

Python na Infraestrutura 
MySQL do Facebook
Python na Infraestrutura 
MySQL do Facebook

Python na Infraestrutura 
MySQL do Facebook

 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1
 
java 8 Hands on Workshop
java 8 Hands on Workshopjava 8 Hands on Workshop
java 8 Hands on Workshop
 

Mehr von 용 최 (6)

우분투한국커뮤니티 수학스터디결과보고
우분투한국커뮤니티 수학스터디결과보고우분투한국커뮤니티 수학스터디결과보고
우분투한국커뮤니티 수학스터디결과보고
 
Java와 Python의 만남: Jython과 Sikuli
Java와 Python의 만남: Jython과 SikuliJava와 Python의 만남: Jython과 Sikuli
Java와 Python의 만남: Jython과 Sikuli
 
Python on Android
Python on AndroidPython on Android
Python on Android
 
Python 웹 프로그래밍
Python 웹 프로그래밍Python 웹 프로그래밍
Python 웹 프로그래밍
 
Python 활용: 이미지 처리와 데이터 분석
Python 활용: 이미지 처리와 데이터 분석Python 활용: 이미지 처리와 데이터 분석
Python 활용: 이미지 처리와 데이터 분석
 
Python 생태계의 이해
Python 생태계의 이해Python 생태계의 이해
Python 생태계의 이해
 

Kürzlich hochgeladen

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Kürzlich hochgeladen (20)

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 

Python 표준 라이브러리

  • 1. 파이썬 표준 라이브러리 정보기술 시대에 유익한 파이썬 프로그래밍 – 제 7 강 동양미래대학교 2015.7 최용 <sk8er.choi@gmail.com>
  • 2. 강의 주제 • Python 표준 라이브러리 일부 소개 • 텍스트 프로세싱: 문자열 포매팅 • 데이터 타입: datetime, calendar, collections, copy • 숫자 및 수학 모듈: math, random • 함수형 프로그래밍 • map(), filter() 내장 함수 • functools, itertools 모듈 • 파일 및 디렉터리 접근: os.path, pathlib, fnmatch • 데이터 영속성: pickle • 파일 포맷: csv • 운영체제 일반 서비스: os • 파이썬 런타임: sys • 개발 도구: unittest, doctest • 데이터베이스, 인터넷 관련 모듈은 9강에서 다룸 더그 헬먼 저, 정승원 역,<The Python Standard Library by Example>
  • 4. Advanced String Formatting • ‘%’ 연산자의 제약을 극복하기 위한 새로운 포매팅 방법 • 문자열 메소드 format() 또는 내장 함수 format() • Format Specification Mini-Language
  • 5. Advanced String Formatting – positional argument, keyword argument >>> '조{0}모{1}'.format('삼', '사') # positional argument '조삼모사' >>> '조{a}모{b}'.format(a='삼', b='사') # keyword argument '조삼모사' >>> '조{}모{}'.format('삼', '사') # 생략(묵시적으로 위치 지정) '조삼모사' >>> '{0}{1}{2}{3}{4}{5}{6}'.format('빨', '주', '노', '초', '파', '남', '보') '빨주노초파남보' >>> '{6}{5}{4}{3}{2}{1}{0}'.format('빨', '주', '노', '초', '파', '남', '보') '보남파초노주빨'
  • 6. Advanced String Formatting – width, alignment >>> '조{:2}모{:2}'.format('삼', '사') # 폭(width) 2 '조삼 모사 ' >>> for n in (1, 23, 456): ... print('{:>4}'.format(n)) # 오른쪽 정렬, 폭 4 ... 1 23 456 >>> for fruit in ('apple', 'banana', 'strawberry'): ... print('{:^10}'.format(fruit)) # 가운데 정렬, 폭 10 ... apple banana strawberry
  • 7. Advanced String Formatting – presentation types >>> '{:s}등'.format('일') # 's': 문자열(string) '일등' >>> '{:d}등'.format(1) # 'd': 십진수(decimal) '1등' >>> '{:2.1f}도'.format(36.55) # 'f': 고정소수점(fixed point) '36.5도' >>> '{:2.1e}도'.format(36.55) # 'e': 지수 표기(exponent notation) '3.7e+01도'
  • 8. Advanced String Formatting – presentation types >>> fmt = '{:.2%} {:s} 외에는 아무 것도 넣지 않았습니다.' # '%': 백분율 >>> for n in [0.99, 0.999, 0.9999, 0.99999]: ... print(fmt.format(n, '꿀')) ... 99.00% 꿀 외에는 아무 것도 넣지 않았습니다. 99.90% 꿀 외에는 아무 것도 넣지 않았습니다. 99.99% 꿀 외에는 아무 것도 넣지 않았습니다. 100.00% 꿀 외에는 아무 것도 넣지 않았습니다.
  • 9. Advanced String Formatting – type conversion >>> '{:s}등'.format(1) # int에 대해서 포맷 's' 사용 못함 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Unknown format code 's' for object of type 'int' >>> '{!r:}등'.format(1) # repr()을 사용하여 문자열로 변환 '1등' >>> '{!s:}등'.format(1) # str()을 사용하여 문자열로 변환 '1등'
  • 11. re • 텍스트 패턴 매칭을 위한 강력한 도구 • https://developers.google.com/edu/python/regular-expressions >>> import re >>> s = 'an example word:cat!!' >>> m = re.search(r'word:www', s) >>> if m: ... print('found', m.group()) ... else: ... print('did not find') ... found word:cat >>> print('1n2n3') 1 2 3 >>> print(r'1n2n3') 1n2n3
  • 12. re – 기본 패턴 >>> re.search(r'iii', 'piiig') <_sre.SRE_Match object; span=(1, 4), match='iii'> >>> re.search(r'igs', 'piiig') # match=None >>> re.search(r'..g', 'piiig') # . -- any single char <_sre.SRE_Match object; span=(2, 5), match='iig'> >>> re.search(r'ddd', 'p123g') # d -- [0-9] <_sre.SRE_Match object; span=(1, 4), match='123'> >>> re.search(r'www', '@@abcd!!') # w -- [a-zA-Z0-9_] <_sre.SRE_Match object; span=(2, 5), match='abc'> >>> re.search(r'^...', 'p123g') # ^ -- start <_sre.SRE_Match object; span=(0, 3), match='p12'> >>> re.search(r'...$', 'p123g') # $ -- end <_sre.SRE_Match object; span=(2, 5), match='23g'>
  • 13. re – Repitation (반복) • + -- 1회 이상 나타남(occurrences) • * -- 0회 이상 • ? -- 0 또는 1회 >>> re.search(r'er+y', 'strawberry') <_sre.SRE_Match object; span=(6, 10), match='erry'> >>> re.search(r'e+y', 'strawberry') >>> re.search(r'e*y', 'strawberry') <_sre.SRE_Match object; span=(9, 10), match='y'> >>> re.search(r'er?y', 'strawberry') >>> re.search(r'ex?.+y', 'strawberry') <_sre.SRE_Match object; span=(6, 10), match='erry'>
  • 14. re – 그룹 추출 >>> s = 'purple alice-b@google.com monkey dishwasher' >>> m = re.search('([w.-]+)@([w.-]+)', s) >>> if m: ... print(m.group()) ... print(m.group(1)) ... print(m.group(2)) ... alice-b@google.com alice-b google.com
  • 15. re – findall >>> s = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher' >>> emails = re.findall(r'[w.-]+@[w.-]+', s) >>> for email in emails: ... print(email) ... alice@google.com bob@abc.com
  • 17. datetime • 날짜, 시간에 관련된 기능 >>> from datetime import datetime >>> datetime.now().weekday() # 0: 월요일, 6: 일요일 3 >>> datetime.now().isoweekday() # 1: 월요일, 7: 일요일 4 >>> tw = todays_weekday = datetime.now().isoweekday() >>> if 1 <= tw <= 5: ... print('차량번호 끝자리가 %d 또는 %d인 차량은 주차금지' % (tw, tw + 5)) ... else: ... print('주말은 차량 5부제를 시행하지 않습니다') ...
  • 18. calendar >>> import calendar >>> calendar.prmonth(2015, 7) July 2015 Mo Tu We Th Fr Sa Su 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 >>> calendar.setfirstweekday(6) >>> calendar.prmonth(2015, 7) July 2015 Su Mo Tu We Th Fr Sa 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 >>> calendar.isleap(2014) False >>> calendar.isleap(2016) True 6: Sunday
  • 20. collections • Python의 일반 목적 내장 자료형(dict, list, set, tuple)을 대체하는 특수한 컨테이너 자료형 https://docs.python.org/3/library/collections.html
  • 21. collections.ChainMap >>> from collections import ChainMap >>> default_settings = {'a': 1, 'b': 2} >>> custom_settings = {'b': 10, 'c': 11} >>> applied_settings = ChainMap(custom_settings, default_settings) >>> applied_settings ChainMap({'b': 10, 'c': 11}, {'b': 2, 'a': 1}) >>> for k, v in applied_settings.items(): ... print(k, v) ... b 10 c 11 a 1 http://stackoverflow.com/questions/23392976/what-is-the-purpose-of-collections-chainmap
  • 22. collections.Counter >>> import collections >>> C = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']) >>> C Counter({'b': 3, 'a': 2, 'c': 1}) >>> C.update('abcdaab') >>> C Counter({'b': 5, 'a': 5, 'c': 2, 'd': 1})
  • 23. collections.deque – double-ended queue >>> import collections >>> d = collections.deque([1, 2], maxlen=5) >>> d.append(3) >>> d deque([1, 2, 3], maxlen=5) >>> d.appendleft(4) >>> d deque([4, 1, 2, 3], maxlen=5) >>> d.append(5) >>> d deque([4, 1, 2, 3, 5], maxlen=5) >>> d.append(6) >>> d deque([1, 2, 3, 5, 6], maxlen=5) >>> d.pop() 6 >>> d deque([1, 2, 3, 5], maxlen=5) >>> d.popleft() 1 >>> d deque([2, 3, 5], maxlen=5) >>> d.extend([7, 8]) >>> d deque([2, 3, 5, 7, 8], maxlen=5) >>> list(d) [2, 3, 5, 7, 8]
  • 24. collections.defaultdict >>> import collections >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = collections.defaultdict(list) >>> for k, v in s: ... d[k].append(v) ... >>> d defaultdict(<class 'list'>, {'red': [1], 'yellow': [1, 3], 'blue': [2, 4]}) >>> list(d.items()) [('red', [1]), ('yellow', [1, 3]), ('blue', [2, 4])] https://docs.python.org/3/library/collections.html#defaultdict-examples
  • 25. collections.namedtuple >>> import collections >>> Point = collections.namedtuple('Point', ['x', 'y']) >>> p = Point(11, y=22) >>> print(p[0], p[1]) # indexable like plain tuple 11 22 >>> print(p.x, p.y) # field accessible by name 11 22 >>> p # readable __repr__ Point(x=11, y=22) https://docs.python.org/3/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields
  • 26. collections.OrderedDict >>> d = {} >>> d['a'] = 'A' >>> d['b'] = 'B' >>> d['c'] = 'C' >>> d['d'] = 'D' >>> d['e'] = 'E' >>> d {'d': 'D', 'b': 'B', 'c': 'C', 'a': 'A', 'e': 'E'} >>> import collections >>> od = collections.OrderedDict() >>> od['x'] = 'X' >>> od['y'] = 'Y' >>> od['a'] = 'A' >>> od['b'] = 'B' >>> od['c'] = 'C' >>> od OrderedDict([('x', 'X'), ('y', 'Y'), ('a', 'A'), ('b', 'B'), ('c', 'C')])
  • 27. collections – UserDict, UserList, UserString • dict, list, string을 직접 상속할 수 없었을 때에 사용한 wrapper • 현재는 dict, list, str을 바로 상속할 수 있으므로 필요성이 낮음
  • 28. collections.abc >>> from abc import * >>> class C(metaclass=ABCMeta): ... @abstractmethod ... def absMethod(self): ... pass ... >>> c = C() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class C with abstract methods absMethod >>> class B(C): ... def absMethod(self): ... print("Now a concrete method") ... >>> b = B() >>> b.absMethod() Now a concrete method http://autonomist.tistory.com/entry/펌-Python-3-입문-Part-2-고급-주제
  • 29. copy – Shallow and Deep Copy 얕은 복사(shallow copy) >>> L1 = [['apple', 'banana'], 'milk'] >>> import copy >>> L2 = copy.copy(L1) >>> L1[0].append('orange') >>> L1[1] = 'cheese' >>> L1 [['apple', 'banana', 'orange'], 'cheese'] >>> L2 [['apple', 'banana', 'orange'], 'milk'] 깊은 복사(deep copy) >>> L1 = [['apple', 'banana'], 'milk'] >>> import copy >>> L2 = copy.deepcopy(L1) >>> L1[0].append('orange') >>> L1[1] = 'cheese' >>> L1 [['apple', 'banana', 'orange'], 'cheese'] >>> L2 [['apple', 'banana'], 'milk']
  • 30. 숫자 및 수학 모듈 Numeric and Mathematical Modules
  • 31. math >>> math.pi # 원주율 값 3.141592653589793 >>> math.pow(2, 5) # 2 * 2 * 2 * 2 * 2 32.0 >>> math.sqrt(144) # 144의 제곱근 12.0 >>> math.factorial(4) # 1 * 2 * 3 * 4 24
  • 32. random 모듈 • Pseudo random number generator • Uniform selection • 보안 목적으로는 사용 금지 os.urandom() 또는 SystemRandom 사용 • https://docs.python.org/3.4/library/random.html 참조
  • 33. random.choice() >>> import random >>> dice = [i for i in range(1, 7)] >>> dice [1, 2, 3, 4, 5, 6] >>> random.choice(dice) 4 >>> random.choice(dice) 6 >>> random.choice(dice) 2 >>> random.choice(dice) 2 >>> random.choice('aeiou') 'u' >>> random.choice('aeiou') 'a' >>> random.choice('aeiou') 'i' >>> random.choice('aeiou') 'a' >>> random.choice('aeiou') 'a' >>> random.choice('aeiou') 'u'
  • 34. random.randrange() >>> random.randrange(7) 2 >>> random.randrange(7) 4 >>> random.randrange(7) 0 >>> random.randrange(7) 3 >>> random.randrange(7) 1 >>> random.randrange(7) 1 >>> random.randrange(7) 0 >>> random.randrange(3, 30, 3) 15 >>> random.randrange(3, 30, 3) 24 >>> random.randrange(3, 30, 3) 3 >>> random.randrange(3, 30, 3) 12 >>> random.randrange(3, 30, 3) 27 >>> random.randrange(3, 30, 3) 21 >>> random.randrange(3, 30, 3) 24
  • 35. random.shuffle() >>> dice [1, 2, 3, 4, 5, 6] >>> random.shuffle(dice) >>> dice [5, 2, 4, 3, 1, 6] >>> new_dice = tuple([i for i in range(1, 7)]) >>> new_dice (1, 2, 3, 4, 5, 6) >>> random.shuffle(new_dice) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:Python34librandom.py", line 272, in shuffle x[i], x[j] = x[j], x[i] TypeError: 'tuple' object does not support item assignment
  • 37. 절차적 vs 함수형 명령형(Imperative), 절차적(procedural) 접근 • 계산을 실행하는 순서를 기술 • 반복(Loop) • 상태(state): 중간 결과 저장 • 상태에 따라 결과가 바뀌는 부작용이 있음. 선언적(declarative), 함수형(functional) 접근 • 무엇을 하려고 하는지를 기술 • 재귀(recursion) • Loop와 state가 없음 • 상태로 인한 부작용을 배제
  • 38. map() 내장 함수 • Iterable object의 각 원소에 대하여 함수를 적용 >>> prime_nums = (1, 2, 3, 5, 7, 9, 11, 13) >>> [p * p for p in prime_nums] [1, 4, 9, 25, 49, 81, 121, 169] >>> list(map(lambda x: x * x, prime_nums)) [1, 4, 9, 25, 49, 81, 121, 169] >>> data = '성 춘향| 010-300-3333 |광한루|' >>> data.split('|') ['성 춘향', ' 010-300-3333 ', '광한루', ''] >>> list(map(str.strip, data.split('|'))) ['성 춘향', '010-300-3333', '광한루', ''] 맵: 네모()
  • 39. filter() 내장 함수 • 원소들을 기준(함수가 True를 반환)에 따라 걸러냄 • filter 타입의 객체를 반환 >>> multiples_of_3 = range(3, 31, 3) # 30 이하의 3의 배수 >>> tuple(multiples_of_3) (3, 6, 9, 12, 15, 18, 21, 24, 27, 30) >>> tuple(filter(lambda x: x % 15 != 0, multiples_of_3)) # 그 중 15의 배수가 아닌 것 (3, 6, 9, 12, 18, 21, 24, 27) >>> langs = ('C', 'Java', 'Perl', 'PHP', 'Python') >>> tuple(filter(lambda s: s.startswith('P'), langs)) # 'P' 자로 시작하는 언어 ('Perl', 'PHP', 'Python') 필터: 파란색이냐()
  • 40. itertools – count() >>> import itertools >>> natural = itertools.count(1) >>> next(natural) 1 >>> next(natural) 2 >>> next(natural) 3 >>> even = itertools.count(2, 2) >>> next(even) 2 >>> next(even) 4 >>> next(even) 6 >>> negative = itertools.count(-1, -1) >>> next(negative) -1 >>> next(negative) -2 >>> next(negative) -3
  • 41. itertools – cycle() >>> import itertools >>> day = itertools.cycle('월화수목금금금') >>> next(day) '월' >>> next(day) '화' >>> next(day) '수' >>> next(day) '목' >>> next(day) '금' >>> next(day) '금' >>> next(day) '금' >>> next(day) '월' >>> next(day) '화' >>> next(day) '수' >>> next(day) '목' 월 화 수 목금 금 금
  • 42. functools – reduce() 함수 • 주어진 함수를 이용하여 원소들을 결합 >>> L = [1, 2, 3, 4, 5] >>> import functools >>> functools.reduce(lambda a, x: a + x, L) 15 https://docs.python.org/3/library/functools.html 참조
  • 43. 파일과 디렉터리 접근 File and Directory Access
  • 44. os.path – 일반적인 경로명 조작 >>> import os >>> print(os.path.join('c:python34', 'python.exe')) c:python34python.exe >>> print(os.path.join('/usr/bin', 'python')) /usr/binpython >>> print(os.path.expanduser('~')) C:UsersYong Choi >>> print(os.path.join(os.path.expanduser('~'), 'documents')) C:UsersYong Choidocuments http://juehan.github.io/DiveIntoPython3_Korean_Translation/comprehensions.html#ospath
  • 45. pathlib – 객체 지향 파일시스템 경로(ver. 3.4) • Pure Path: 파일 시스템에 실제로 접근하지 않음 • Concrete Path: Pure Path 클래스들의 서브클래스. Path 객체에 대한 시스템 콜을 위한 메소드를 제공 >>> from pathlib import * >>> p = Path('c:/python34/python.exe') >>> p WindowsPath('c:/python34/python.exe') >>> p.exists() True >>> PurePath('/usr/bin/python3').parts ('', 'usr', 'bin', 'python3') https://docs.python.org/3/library/pathlib.html
  • 46. pathlib – properties >>> PureWindowsPath('c:/Program Files/').drive 'c:' >>> PurePosixPath('my/library/setup.py').name 'setup.py' >>> PureWindowsPath('//some/share/setup.py').name 'setup.py' >>> PurePosixPath('my/library/setup.py').suffix '.py' >>> PurePosixPath('my/library.tar.gz').suffix '.gz' >>> PurePosixPath('my/library.tar.gz').suffixes ['.tar', '.gz'] >>> PurePosixPath('my/library.tar.gz').stem 'library.tar'
  • 47. pathlib – methods >>> PureWindowsPath('c:/Windows').as_uri() 'file:///c:/Windows' >>> PurePosixPath('/etc').joinpath('passwd') PurePosixPath('/etc/passwd') >>> PurePath('/a/b/c.py').match('b/*.py') True >>> PurePath('/a/b/c.py').match('a/*.py') False >>> PureWindowsPath('b.py').match('*.PY') True >>> PurePosixPath('b.py').match('*.PY') False
  • 48. fnmatch – 파일명 매칭 >>> import fnmatch >>> import os >>> matches = [] >>> for root, dirnames, filenames in os.walk('C:Python34'): ... for filename in fnmatch.filter(filenames, '*.exe'): ... matches.append(os.path.join(root, filename)) ... >>> matches ['C:Python34python.exe', 'C:Python34pythonw.exe', 'C:Python34Libdi stutilscommandwininst-10.0-amd64.exe', 'C:Python34Libdistutilscomman dwininst-10.0.exe', 'C:Python34Libdistutilscommandwininst-6.0.exe',
  • 50. pickle • Python 개체를 파일에 저장 • 피클 >>> import pickle >>> favorite_color = {'lion': 'yellow', 'kitty': 'red'} >>> pickle.dump(favorite_color, open('favorite_color', 'wb')) • 언피클 >>> import pickle >>> favorite_color = pickle.load(open('favorite_color', 'rb')) >>> favorite_color {'kitty': 'red', 'lion': 'yellow'} https://wiki.python.org/moin/UsingPickle https://commons.wikimedia.org/wiki/File:Pickled_Walnuts_Jar.jpg
  • 53. csv.writer >>> import csv >>> with open('eggs.csv', 'w', newline='') as csvfile: ... spamwriter = csv.writer(csvfile, delimiter=' ', ... quotechar='|', quoting=csv.QUOTE_MINIMAL) ... spamwriter.writerow(['Spam'] * 5 + ['Baked Beans']) ... spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) ... 40 37 Spam Spam Spam Spam Spam |Baked Beans| Spam |Lovely Spam| |Wonderful Spam|
  • 54. csv.reader Spam Spam Spam Spam Spam |Baked Beans| Spam |Lovely Spam| |Wonderful Spam| >>> import csv >>> with open('eggs.csv', newline='') as csvfile: ... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') ... for row in spamreader: ... print(', '.join(row)) ... Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam https://docs.python.org/3/library/csv.html
  • 55. 운영 체제 일반 서비스 Generic Operating System Services
  • 56. os >>> os.environ['HOME'] 'C:UsersYong Choi' >>> os.environ['NUMBER_OF_PROCESSORS'] '4' >>> os.getcwd() 'C:UsersYong Choi' >>> os.chdir('Program Files') >>> os.getcwd() 'C:Program Files'
  • 58. sys >>> sys.platform 'win32' >>> sys.byteorder 'little' >>> sys.getwindowsversion() sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') >>> sys.version_info sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0) >>> sys.winver '3.4'
  • 59. sys.argv • sys_argv_test.py import sys for i in range(len(sys.argv)): print('sys.argv[{:d}]: {:s}'.format(i, sys.argv[i])) > py -3 sys_argv_test.py a b c d sys.argv[0]: sys_argv_test.py sys.argv[1]: a sys.argv[2]: b sys.argv[3]: c sys.argv[4]: d
  • 60. sys.path • D:summer_pythonlecture07mycalendar.py import calendar def prmonth(theyear, themonth, w=0, l=0): calendar.setfirstweekday(6) calendar.prmonth(theyear, themonth, w, l) >>> import sys >>> sys.path.append('D:summer_pythonlecture07') >>> import mycalendar >>> mycalendar.prmonth(2015, 7)
  • 62. unittest • test fixture: 테스트를 수행하기 위한 준비와 뒷정리 • test case: 테스트의 개별 단위 • test suite: 함께 수행할 테스트들을 묶은 것 • test runner: 테스트의 수행 및 그 결과를 사용자에게 보여주는 것까지
  • 63. unittest - assertEqual import unittest def fun(x): return x + 1 class MyTest(unittest.TestCase): def test(self): self.assertEqual(fun(3), 4) if __name__ == '__main__': unittest.main() . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK http://docs.python-guide.org/en/latest/writing/tests/
  • 64. unittest – failUnless, failIf import unittest def IsOdd(n): return n % 2 == 1 class IsOddTests(unittest.TestCase): def testOne(self): self.failUnless(IsOdd(1)) def testTwo(self): self.failIf(IsOdd(2)) if __name__== '__main__': unittest.main() .. ------------------------------------------- Ran 2 tests in 0.000s OK http://www.openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html
  • 65. unittest – assertRaises import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) with self.assertRaises(TypeError): s.split(2) if __name__ == '__main__': unittest.main() https://docs.python.org/3.4/library/unittest.html#basic-example
  • 66. doctest def square(x): """Squares x. >>> square(2) 4 >>> square(-3) 9 """ return x + x if __name__ == '__main__': import doctest doctest.testmod() > python mysquare.py ******************************************* File "mysquare.py", line 6, in __main__.square Failed example: square(-3) Expected: 9 Got: -6 ******************************************* 1 items had failures: 1 of 2 in __main__.square ***Test Failed*** 1 failures.
  • 67. 2to3 • Python 2로 작성된 스크립트를 Python 3로 자동 변환 > dir /b hello.py > type hello.py print 'Hello' > 2to3 -w hello.py > dir /b hello.py.bak hello.py > type hello.py print('Hello') print 'Hello' print('Hello')2to3

Hinweis der Redaktion

  1. NAME fnmatch - Filename matching with shell patterns. DESCRIPTION fnmatch(FILENAME, PATTERN) matches according to the local convention. fnmatchcase(FILENAME, PATTERN) always takes case in account. The functions operate by translating the pattern into a regular expression. They cache the compiled regular expressions for speed. The function translate(PATTERN) returns a regular expression corresponding to PATTERN. (It does not compile it.)
  2. On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.
  3. On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.