%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>
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
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
32. random 모듈
• Pseudo random number generator
• Uniform selection
• 보안 목적으로는 사용 금지
os.urandom() 또는 SystemRandom 사용
• https://docs.python.org/3.4/library/random.html 참조
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')
필터: 파란색이냐()
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 참조
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
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
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
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.)
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.
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.