# Exception, 예외
예상이 가능한 예외와 예상이 불가능한 예외로 나눌 수 있다.
# 예상 가능한 예외
발생 여부를 사전에 인지할 수 있는 예외
사용자의 잘못된 입력, 파일 호출시 파일 없음
개발자가 반드시 명시적으로 정의해야 한다
# 예상 불가능한 예외
인터프리터 과정에서 발생하는 예외, 또는 개발자 실수
리스트의 범위를 넘어가는 값 호출, 정수 0으로 나누는 경우
수행 불가시 인터프리터가 자동으로 호출
# Exception Handling, 예외 처리
예외가 발생할 경우 후속 조치가 필요하다.
없는 파일을 호출 할 경우 파일이 없음을 알려주고,
게임이 이상하게 종료되는 경우에는 게임정보를 자동으로 저장하고,
즉, 모든 잘못된 상황에 대해 대처가 필요하다.
try:
예외 발생 가능 코드
except <Exception Type>:
예외 발생시 대응하는 코드
else:
예외가 발생하지 않을 때 동작하는 코드
finally:
모두 끝난뒤 실행되는 코드
# 0으로 숫자를 나눌 때 예외처리 하기
for i in range(10):
try:
print(10/i)
except ZeroDivisionError: # 에러가 핸들링되면 에러난다고 종료되는 것이 아니라 계속진행된다.
print("Not divided by 0")
except Exception as e: # 이 구문을 써주지 않으면 핸들링 되지 않았을 경우 진행이 종료된다.
print(e)
# raise
필요에 따라 강제로 Exception을 발생시켜야 하는 경우도 있다.
while True:
value = input("변환할 정수 값을 입력해주세요")
for digit in value:
if digit not in "0123456789":
raise ValueError("숫자값을 입력하지 않으셨습니다")
print("정수값으로 변환된 숫자 -", int(value))
# assert
특정 조건에 만족하지 않을 경우 예외 발생
def get_binary_nmubmer(decimal_number):
assert isinstance(decimal_number, int)
return bin(decimal_number)
print(get_binary_nmubmer(10))
# file handling
기본적인 파일 종류로 text파일과 binary파일로 나눌 수 있다.
# 파이썬 file i/o
f = open("<파일이름>", "접근 모드")
f.close()
f = open("i_have_a_dream.txt", "r")
contents = f.read()
print(contents)
f.close()
# with 구문을 사용하면 close를 따로 사용하지 않아도 된다.
with open("i_have_a_dream.txt", "r") as my_file:
contents = my_file.read()
print(type(contents), contents)
with open("i_have_a_dream.txt", "r") as my_file:
content_list = my_file.readlines() # 파일 전체를 list로 반환
print(type(content_list))
print(content_list)
with open("i_have_a_dream.txt", "r") as my_file:
i = 0
while True:
line = my_file.readline()
if not line:
break
print(str(i) + "===" + line.replace("\n", ""))
i = i + 1
with open("i_have_a_dream.txt", "r") as my_file:
contents = my_file.read()
word_list = contents.split(" ")
line_list = contents.split("\n")
print("Total Number of Characters :", len(contents))
print("Total Number of Words :", len(word_list))
print("Total Number of Lines :", len(line_list))
f = open("count_log.txt", 'w', encoding="utf8")
for i in range(1, 11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
f.close()
with open("count_log.txt", 'a', encoding="utf8") as f:
for i in range(1, 11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
# directory 다루기
os 모듈을 사용해서 직접적으로 폴더를 다룰 수 있다.
import os
os.mkdir("log")
디렉토리가 있는지 확인하기
if not os.path.isdir("log"): # 또는 os.path.exists("log")
os.mkdir("log")
파일 경로 작성 및 복사
import shutill
source = "i_have_a_dream.txt"
dest = os.path.join("abc", "test.txt")
shutill.copy(source, dest)
파일 경로 관련된 내용은 pathlib을 사용해도 괜찮다.
# pickle
파이썬의 객체를 영속화하는 객체
데이터, 객체 등 실행중 정보를 저장하고 불러와서 사용한다.
저장해야 하는 정보와 계산 결과 등 활용하는 경우가 많다.
import pickle
f = open("list.pickle", "wb")
test = [1, 2, 3, 4, 5]
pickle.dump(test, f)
f.close()
f = open("list.pickle", "rb")
test_pickle = pickle.load(f)
print(test_pickle)
f.close()
# logging
프로그램이 실행되는 동안 일어나는 정보를 기록으로 남긴다.
유저의 접근, 프로그램의 예외, 특정 함수 사용 이력 등을 남길때 사용한다.
콘솔 화면에 출력할 수도 있고, 파일에 남길 수도 있고, db에 남길 수도 있다.
실행시점에 남겨야 하는 기록과, 개발시점에 남겨야 하는 기록이 있다.
import logging
logger = logging.getLogger("main")
logging.basicConfig(level=logging.DEBUG)
logger.setLevel(logging.INFO)
steam_handler = logging.fileHandler("my.log", mode="w", encoding="utf8")
logger.addHandler(steam_handler)
logging.debug("틀렸잖아!") # 개발시 처리 기록을 남겨야 하는 정보
logging.info("확인해!") # 처리가 진행되는 동안의 정보 # 서버시작, 종료 등
logging.warning("조심해!") # 파이썬의 기본 로깅 레벨
logging.error("에러났어!!")
logging.critical("망했다...")
# configparser
import configparser
config = configparser.ConfigParser()
config.sections()
config.read('example.cfg')
config.sections()
for key in config['SectionOne']:
print(key)
print['SectionOne']['status']
# example.cfg
[SectionOne]
status: single
name: derek
value: yes
age: 30
single: true
[SectionTwo]
FavoriteColor = Green # = 도 사용 가능하다.
[SectionThree]
FamilyName: Johnson
# argparser
console 창에서 프로그램 실행시 setting 정보를 저장한다.
거의 모든 console 기반 파이썬 프로그램 기본으로 제공
특수 모듈도 많이 존재하지만(TF), 일반적으로 argparse를 사용
command line option이라고 부른다.
import argparse
parser = argparse.ArgumentParser(description='Sum two integers.')
# 짧은 이름, 긴 이름, 표시명, help 설명, argument type
parser.add_argument('-a', '--a_value', dest='A_value', help='A integers', type=int)
parser.add_argument('-b', '--b_value', dest='B_value', help='B integers', type=int)
args = parser.parse_args()
print(args)
print(args.a)
print(args.b)
print(args.a + args.b)
# CSV(comma separate values)
필드를 쉼표로 구분한 텍스트 파일
엑셀 양식의 데이러를 프로그램에 상관없이 쓰기 위한 데이터형식이라고 생각하면 된다.
탭(TSV), 빈칸(SSV) 등으로 구분해서 만들기도 한다.
통칭해서 character separated values(csv)로 부르기도 한다.
엑셀에서는 다른 이름으로 저장 기능으로 사용 가능하다.
텍스트 파일 형태로 데이터 처리시 구분자가 문자열 내에 있는 부분은 전처리가 필요하다.
파이썬에서는 csv객체를 제공한다.
import csv
# 파일, 구분자, 구분자무시 문장표시, quotechar에 의해 둘러싸인 레벨
reader = csv.reader(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
import csv
seoung_nam_data = []
header = []
rownum = 0
with open("korea_floating_population_data.csv", "r", encoding="cp949") as p_file:
csv_data = csv.reader(p_file)
for row in csv_data:
if rownum == 0:
header = row
location = row[7]
if location.fine(u"성남시") != -1:
seoung_nam_data.append(row)
rownum += 1
with open("seoung_name_floating_population_data.csv", "w", encoding="utf8") as s_p_file:
writer = csv.writer(s_p_file, delimiter='\t', quotechar="'", quoting=csv.QUOTE_ALL)
writer.writerow(header)
for row in seoung_nam_data:
writer.writerow(row)
# web
팀 버너스리에 의해 1989년 처음 제안됨
물리학자들 간의 정보 교환을 위해 사용
데이터 송수신을 위한 http 프로토콜 사용
# html
웹 상의 정보를 구조적으로 표현하기 위한 언어
제목, 단락, 링크 등의 요소 표시를 위해 tag를 사용한다.
모든 html은 트리 모양의 포함관계를 가진다.
# 정규식
복잡한 문자열 패턴을 정의하는 문자 표현 공식
특정한 규칙을 가진 문자열의 집합을 추출
www.regexr.com 에서 연습 가능
. # 줄바꿈 문자인 \n을 제외한 모든 문자와 매치
* # 앞에 있는 글자를 반복해서 나올 수 있음
+ # 앞에 있는 글자를 1회 이상 반복
{m.n} # 반복 횟수를 지ㅏ정
? # 반복 횟수가 1회
| # or
^ # not
# 파이썬에서 정규식 사용하기
import re
import urllib.request
url = "https://bit.ly/3rxQFS4"
html = urllib.request.urlopen(url)
html_contents = str(html.read())
id_results = re.findall(r"([A-Za-z0-9]+\*\*\*)", html_contents)
for result in id_results:
print(result)
# xml
html과 문법이 비슷, 대표적으로 데이터 저장 방식
정규표현식으로 parsing으로 가능하지만 lxml, BeutifulSoup을 주로 사용한다.
from bs4 import BeutifulSoup
with open("books.xml", "r", encoding="utf8") as books_file:
books_xml = books_file.read()
soup = BeutifulSoup(books_xml, 'lxml')
for book_info in soup.find_all("author"):
print(book_info)
print(book_info.get_text())
# JSON
자바스크립트의 데이터 객체 표현 방식
json 모듈을 사용하여 손쉽게 파싱 및 저장 가능
데이터 저장 및 읽기는 dict type과 상호 호환 가능
웹에서 제공하는 api는 대부분 정보 교환시 json사용
각 사이트마다 developer api의 활용법을 찾아 사용
import json
with open("json_example.json", "r", encoding="utf8") as f:
contents = f.read()
json_data = json.loads(contents)
print(json_data["employees"])
with open("data.json", "w") as f:
json.dump(dict_data, f)
# AI에 분야가 많은것 같은데 어떤 분야가 있는지?
데이터 : 텍스트, 이미지, 타뷸라, 사운드, 3d
ai종류 : classification, clustering, recommendation, Reinforce learning, 생성
'ai tech' 카테고리의 다른 글
ai tech 7일차 (0) | 2021.01.26 |
---|---|
ai tech 6일차 (0) | 2021.01.25 |
ai tech 4일차 (0) | 2021.01.21 |
ai tech 3일차 (0) | 2021.01.20 |
ai tech 2일차 (0) | 2021.01.19 |