2018-01-23 TIL WPS 12.파이썬-예외처리, 파일 입출력

정규표현식 실습

다음 텍스트를 이용하여 문제 풀기

story = ‘'’Born to the prestigious Crownguards, the paragon family of Demacian service, Luxanna was destined for greatness. She grew up as the family’s only daughter, and she immediately took to the advanced education and lavish parties required of families as high profile as the Crownguards. As Lux matured, it became clear that she was extraordinarily gifted. She could play tricks that made people believe they had seen things that did not actually exist. She could also hide in plain sight. Somehow, she was able to reverse engineer arcane magical spells after seeing them cast only once. She was hailed as a prodigy, drawing the affections of the Demacian government, military, and citizens alike.

As one of the youngest women to be tested by the College of Magic, she was discovered to possess a unique command over the powers of light. The young Lux viewed this as a great gift, something for her to embrace and use in the name of good. Realizing her unique skills, the Demacian military recruited and trained her in covert operations. She quickly became renowned for her daring achievements; the most dangerous of which found her deep in the chambers of the Noxian High Command. She extracted valuable inside information about the Noxus-Ionian conflict, earning her great favor with Demacians and Ionians alike. However, reconnaissance and surveillance was not for her. A light of her people, Lux’s true calling was the League of Legends, where she could follow in her brother’s footsteps and unleash her gifts as an inspiration for all of Demacia.’’’

아래 실습들은 위의 스토리 문자열을 소스로 사용한다.

문제 1) {m}패턴지정자를 사용해서 a로 시작하는 4글자 단어를 전부 찾는다.

문제 2) r로 끝나는 모든 단어를 찾는다.

문제 3) a,b,c,d,e중 아무 문자나 3번 연속으로 들어간 단어를 찾는다. ex) b[eca]me

문제 4) re.sub를 사용해서 ,로 구분된 앞/뒤 단어에 대해 앞단어는 대문자화 시키고, 뒷단어는 대괄호로 감싼다. 이 과정에서, 각각의 앞/뒤에 before, after그룹 이름을 사용한다.

문제 1)

re.compile = 정규 표현식을 컴파일 해두어 변수로 만듬

p = re.compile(r'\ba\w{3}\b')
re.findall(p, story)

실행결과 :
['also', 'able']

re.finditer = 반복 가는한 interator를 리턴해줌

p = re.compile(r'\ba\w{3}\b')

for match_object in re.finiter(p, story):
	print(match_object.group())

실행결과 : 
also
able

문제 2)

re.findall(r'\w+r\b', story)

문제 3)

re.findall(r'w*[abcde]{3}\w*', story)

문제 4)

  • before와 after가 잘 골라졌는지 확인
p = re.compile(r'(?P<before>\w+)\s*,\s*(?P<after>\w+)')

for match_object in re.finditer(p, story):
	print('before: ', match_object.group('before'))
	print('after: ', match_object.group('after'))
  • re.sub문서를 보면 그룹을 썼을 경우 \g 또는 \g를 이용해 그룹에 접근할 수 있다.
s2 = re.sub(p, '\g<after>, \g<before>', sotry)
print(s2)

출력 결과를 보면 after와 before의 단어가 바뀐 것을 확인할 수 있다.

def sub_function(match_object):
	return f'{match_object.group("before").upper()}, [{match_object.group("after")}]'
	
s2 = re.sub(p, sub_function, story)
print(s2)

한 줄로 짧게 표현하는 것 보다 아래처럼 표현하는 것이 가독성이 좋다. 그렇지 않으면 나중에 봤을 때 본인도 모른다.

def sub_function(match_object):

	before_string = match_object.group('before').upper()
	after_string = f'[{match_object.group("after")}]'
	
	return '{}, {}'.format(
			before_string,
			after_string
	)
	
s2 = re.sub(p, sub_function, story)
print(s2)

예외처리

오류를 안전하게 처리하고, 강제종료 되지 않고 오류 발생 후 처리할 루틴을 실행

기본적인 형태

try:
	시도할 코드
except:
	에러가 발생할  실행되는 코드

실습해보기

  • 리스트의 범위를 넘어간 경우, IndexError를 명시적으로 처리해본다
  • 딕셔너리의 키가 없는 경우, KeyError를 명시적으로 처리해본다

예외사항을 변수로 사용할 경우

try:
	시도할 코드
except <예외클래스> as <변수명>:
	<변수명> 사용한 코드

try ~ else

else문은 try이후 예외가 발생하지 않을 경우 실행된다.

try ~ finally

finally문은 try이후 예외가 발생하건, 하지않건 무조건 마지막에 실행된다.

예외 발생시키기

예외를 발생시킬때는 raise구문을 사용한다.

예외 만들기

내장 클래스 Exception을 상속받아 커스텀 예외를 만들 수 있다. 초기화 메서드에서 예외에서 처리할 데이터를 받고, print문으로 사용되고 싶다면 __str__메서드를 오버라이드 해준다.

파일 입출력

파일 쓰기:write()

iu = '아이유는아이가아니에유'
f = open('iu.txt', 'wt')
f.write(iu)
f.close()

텍스트파일 전체 읽기:read()

f = open('iu.txt', 'rt')
iu = f.read()
f.close()

텍스트파일 줄 단위 읽기: readline()

iu = ''
f = open('iu.txt', 'rt')
	while True:
		line = f.readline()
		if not line:
			break
		iu += line

f.close()
len(iu)

이터레이터를 사용한 텍스트 파일 읽기

iu = ''
f = open('iu.txt', 'rt')
for line in f:
	iu += line

f.close()

텍스트파일 줄 단위 문자열 리스트로 리턴:readlines()

f = open('iu.txt', 'rt')
lines = f.readlines()
f.close()
for line in lines:
	print(line)

자동으로 파일 닫기:with

파일 닫아주는 것에 계속 궁금증을 품고 있었는데 점프 투 파이썬에 이렇게 설명이 나와있었다.

f.close()는 열려 있는 파일 객체를 닫아 주는 역할을 한다. 사실 이 문장은 생략해도 된다. 프로그램을 종료할 때 파이썬 프로그램이 열려 있는 파일의 객체를 자동으로 닫아주기 때문이다. 하지만 close()를 사용해서 열려 있는 파일을 직접 닫아 주는 것이 좋다. 쓰기모드로 열었던 파일을 닫지 않고 다시 사용하려고 하면 오류가 발생하기 때문이다.

with 표현식 as 변수
with open('iu.txt', 'wt') as f:
	f.write(iu)

크롤링 실습

projects안에 crawler폴더 생성 후 깃 이닛 , gitignore 생성, 가상환경 설정

$ mkdir crawler
$ cd crawler
$ git init
$ touch .gitignore
$ pyenv virtualenv 3.6.4 fc-crawler
$ pyenv local fc-crawler

https://www.gitignore.io/에서 linux, macOS, python, Pycharm+all 키워드로 create하여 내용을 .gitignore에 복사

main.py 작성

main.py 파일을 새로 만들었을 때 에러가 생긴다면 가상환경 설정을 해주어야한다. 설정에서

Homework

print(chart)했을 때 멜론 차트에서의 순위, 제목, 가수, 앨범명, 좋아요 수가 나오도록!

Comments