Python 정규 표현식

2020/Python 2019. 11. 21. 18:57
반응형

#정규 표현식
# 단순 문자열 매칭이 아니라 문자열의 패턴으로 검색하는 것
import re

# 사용시 : 패턴 컴파일 -> 패턴 객체의 메서드로 검색 수행
p = re.compile(r"P[a-z]+")
#[] 패턴 1글자 + 1글자 이상
#대문자 P로 시작하고 소문자(a-z) 1글자 이상 있는 문자열
print(p.match("Life"))# 현재 패턴이 life와 일치하는지?
print("p match Python?", p.match("Python"))
print("p match Pizza?", p.match("Pizza"))

source = "Life is too short, you need Python"
# 방법 1. 패턴 컴파일 후 검색 수행
p = re.compile(r"L[a-z]+")
print(p.match("Life"))

# 방법 2. 축약형, 패턴 문자열과 검색 대상 문자열을 함께 제공
print(re.match(r"[A-Z][a-z]+", source))
# 매치된 내용을 추출할 경우 group() 메서드로 뽑을 수 있다
print("Match 된 내용:", re.match(r"[A-Z][a-z]+", source).group())

#축약 문자
# \d(숫자), \w(문자), \s (공백문자)
# \D(숫자가 아닌 것), \W(문자가 아닌 것), \S(공백문자 아닌것)
# search -> 전체 문자열 대상 패턴 검색
#findall -> 전체 문자열 대상 검색 후 list로 반환
# finditer -> 검색 후 iterator(반복자)를 반환
source = "Paint C JavaScript 123 456 Perl Java Python P123 Ruby"
#p로 시작되는 문자열 패턴만 검색해서 iterator을 반환
iter = re.finditer(r"\bp\w+", source, re.IGNORECASE)
#re.IGNORECASE는 대소문자를 구분하지 말고 검색하라는 의미다

for x in iter:
print("검색된 단어:", x)

# 자주 사용될 수 있는 패턴들
# 전화번호의 예
tel = re.compile(r"(\d{2,3})-(\d{3,4})-(\d{4})")
m = tel.match("010-1234-5678")
print("result:", m)
# () 로 묶은 것은 groups() 메서드로 추출
print("groups:", m.groups()) #groups
#매칭된 전체 내용을 추출: group()
print("매칭된 내용:", m.group()) #group

tel= re.compile(r"(?P<area>\d{2,3})-(?P<exchange>\d{3,4})-(?P<number>\d{4})")
# 그룹핑시 (?P<이름>) 형식을 부여하면 매칭 결과에 이름을 부여할 수 있다
# 이름이 부여된 매칭 결과는 groupdict()메서드로 사전으로 반환받을 수 있다.
m = tel.match("010-1234-5678")
print(m.groups()) # 그룹핑된 결과 확인
print(m.group()) #매칭된 전체 결과
print(m.groupdict()) #부여한 이름을 기반으로 한 dict 객체 반환

# 이메일
pattern = r"\w+[\w\.]*@[\w\.]*\.[a-z]+"
source = "skyun.nam@gmail.com"

print(re.match(pattern, source))

# 한글 매칭 (Unicode 기반)
# 한국어 정규식의 예제
source = "English 대한민국 Japan China"
p = re.compile(r"[-]+")
print(p.findall(source))

반응형
블로그 이미지

꽃꽂이하는개발자

,

Python class

2020/Python 2019. 11. 21. 18:52
반응형

# class
"""
-새로운 이름 공간을 지원하는 단위: 데이터의 설계도
- 새로운 클래스는 새로운 자료형을 정의하는 것
- 인스턴스는 이 자료형의 객체를 생성하는 것
- 클래스와 인스턴스는 직접적인 영향을 갖는다

-인스턴스에서 클래스 멤ㅂ와 접근은 자능
-클래스 맴버에서 인스턴스 멤버의 접근은 불가
"""

class MyString(str): # str은 상속받은 새로운 클래스
pass

#특정 클래스를 상속받지 않을 경우, object 상속
s = MyString() # 생성자 호출
print(type(s))

# 어떤 클래스를 상속 받은 클래스잉ㄴ가?
# __bases__ -> 부모의 목록을 튜플로 반환
print("MyString의 부모:", MyString.__bases__)

#특정 부모를 상속받지 않을 경우() 없어도 된다
class myobj: #object를 상속
pass
print(myobj.__bases__)
#파이썬은 여러 부모로부터의 상속을 허용한다

#파이썬은 여러 부모로부터의 상속을 허용한다
class Complex(str, myobj):
# str로부터 모든 맴버들
#myobj로부터 모든 멤버들을 물려받는다
pass

print("Complex의 부모:", Complex.__bases__)

#특정 클래스가 다른 클래스의 자식인지 확인
# issubclass 함수
print("Complex str의 자식인가?", issubclass(Complex,str))

#클래스의 생성
# 인스턴스를 위한 멤버는 항상 self를 붙여준다
class Point:
# 클래스 멤버:
# 클래스 이름 공간 내에 생성
# 모든 인스턴스 맴버 공유
# 클래스 맴버는 인스턴스 생성 없이도 사용할 수 있다.
instance_count = 0

def __init__(self, x = 0, y = 0): # 생성자
#파이썬은 여러 개의 생성자를 만들 수 없으므로
# 범용적으로 사용될 수 있는 유일한 생성자를 작성
self.x = x
self.y = y
Point.instance_count +=1

#소멸자
def __del__(self):
#객체가 제거될 때 호출
Point.instance_count -= 1

#__str__
def __str__(self):#문자열 출력
#str() 호출 혹은 print를 할 때 사용되는 비공식 문자열(일반 사용자 대상)
return "Point x={}, y={}".format(self.x, self.y)
#__repr__
def __repr__(self): #문자열 출력
# 개발자용, 공식문자열
# repr() 함수로 전달 받을 수 있다.
# 이 문자열로 해당 객체를 복원해 낼 수 있어야 한다.
return "Point({},{})".format(self.x,self.y)

def setX(self,x):
self.x = x
def setY(self, y):
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y

#연산자 오버로딩
# 새로운 데이터 타입에 필요한 연산자의 행동을 재정의하는 것
# 산술 연산자 오버로딩 예제
def __add__(self, other):
# Point(self) + other
# other 타입을 점검해서 각기 다른 행독을 취하도록
if isinstance(other, Point):
#합산된 객체가 Point
self.x += other.x
self.y += other.y
elif isinstance(other, int):
self.x += other
self.y += other
else:
self += other

return self
#역이항 연산자 : other + Point
def __radd__(self,other):
if isinstance(other, str):
return other + str(self)
elif isinstance(other, int):
self.x += other
self.y += other
else:
self + other
return self

def bound_class_method():
#생성된 인스턴스를 통해 직접 메서드에 접근하는 방법
p = Point()
# bound 방식의 경우, 첫 번째 인자 self는 전달하지 않아도 된다.
p.setX(10)
p.setY(20)

print("Point p: {}, {}".format(p.getX(), p.getY()))
print(p.getX, p.getY)

#bound_class_method()

def unbound_class_method():
#클래스를 통해 우회 접근하는 경우
# 메서드에 부여된 self 인자에 실제 객체의 주소 전달
p = Point()
Point.setX(p,10)
Point.setY(p,20)

print("Point p: {}, {}".format(Point.getX(p),Point.getY(p)))
print(Point.getX, Point.getY)

#unbound_class_method()

def class_member():
p1 = Point()
p2 = Point()

# 클래스 멤버는 모든 인스턴스에서 접근 가능
# 생성 없이도 직접 접근 가능
print("p1 instance_count의 주소:", id(p1.instance_count))
print("p2 instance_count의 주소:", id(p2.instance_count))

#클래스 멤버의 변경
# 공유 메모리 영역으로 활용할 수 있다

Point.instance_count += 1
p1.instance_count += 1
p2.instance_count += 1
print("p2 instance_count:", p2.instance_count)
print("p1 instance_count:", p1.instance_count)

#class_member()

def lifecycle():
# 생성자와 소멸자 테스트
p1 = Point() # 생성자의 기본값이 사용

print(p1)
print("instance_count:", Point.instance_count)

p2 = Point(x=20, y=30)
print("instance_count:", Point.instance_count)

del p2
print("instance_count:", Point.instance_count)

#lifecycle()

def str_repr():
p = Point(10,20)
print(p) # __str__ 호출
print("포인트 p=" + str(p)) # __str__

#repr 함수를 사용하면 __repr__ 문자열을 얻을 수 있다.
print("repr of p:", repr(p))

#eval 함수를 사용하면 파이썬 코드를 테스트 할 수 있다.
#이때 repr로 전달 받은 문자열(개발자용)을 넘겨주면 같은 객체가 복원되어야 한다.
p_repr = eval(repr(p))
print(p_repr, type(p_repr))

str_repr()

def test_overloading():
# 연산자 오버로딩
p = Point(10, 20)
print("P:", p)
p2 = Point(30,40)
print(p)
print(p2)
print("산술 연산자 테스트:", p + p2)
print("Point+ int:", p+20)

print("int + Point:", 20 + p)
# int 입장에서 Point와의 + 불가
# Point 입장에서 int 합산을 재정의 : 역이항
print("포인트 p = " + p)

test_overloading()

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

sample.zip
1.55MB

#pickle의 사용
#python 객체의 직렬화 - 역직렬화를 위한 모듈
# 프로토콜 버전이 있고, 필요할 경우 특정 프로토콜 버전을 이용해 저장할 수 있다.
# 파일 저장기능은 없고, 직렬화 역직렬화에 대한 기능만 가지고 있다

# pickle 모듈을 import

 

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

 

sample.zip
1.55MB

첫번째로,

입력

여기서는 life is too short, you need python을 입력했지만

다른 문장으로 입력하면 기존에 있던 문장은 사라지고 바꾼 문장이 등록됩니다

 

두번째는,

기존에 있던 데이터에 추가 하는 것을 알아보겠습니다.

이렇게 입력을 하게 되면은 test.txt파일에 "Append 모드로 저장하였습니다." 추가가 되게 됩니다.

 

세번째는 이진 데이터를 복제해 보도록 하겠습니다.

 

rose-flower.jpeg를 복사해서

rose-flower-copy.jpeg생성하게 됩니다.

 

반응형

'2020 > Python' 카테고리의 다른 글

Python class  (0) 2019.11.21
Python pickle(오이지), dump,  (0) 2019.11.21
Python 날짜의 포매팅 -> 문자열로 반환 strftime, formating  (0) 2019.11.20
Python timedelta 두 datetime의 차이값  (0) 2019.11.20
Python datetime  (0) 2019.11.20
블로그 이미지

꽃꽂이하는개발자

,
반응형

strftime는 날짜의 포매팅 -> 문자열로 반환해주는 메서드입니다

현재 datetime을 년-월-일 시: 분: 초 형식으로 바꿔보겠습니다.

current = datetime.datetime.now()

#문자열로 포매팅

print(current.strftime("% Y-%m-%d % H:%M% S"))

#포매팅 -> 0000년 00월 00일

#이렇게 하면 locale Error( 한글 윈도 : ms949)

# 이러면 locale을 import 해주겠습니다

import locale

locale.setlocale(locale.LC_ALL, "ko_KR.UTF-8")

print(current.strftime("%Y년 %m월 %d일"))

 

#문자열로 된 날짜 정보 -> DATETIME : strptime

# strptime(문자열, 해독을 위한 형식 문자열)

s = "2019/11/20 16:00"

dt = datetime.datetime.strptime(s, "%Y/%m/%d %H:%M")

print("해독된 datetime:", dt)

이렇게 출력됩니다^^

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형

현재 날짜 시간과 과거의 날짜시간의 대소를 비교해볼까요?

current = datetime.datetime.now() #현재 날짜 시간

past = datetime.datetime(2001, 1,1) #과거 날짜 시간

print(current >past) #current가 past보다 매리인가요? 

출력해보면 True값이 뜨게 됩니다

 

# 두 datetime은 차이값을 구할 수 있을까요? 

diff = current - past

print(diff)

이렇게 출력이 되는군요^^

 

#timedelta total_second -> 모든 속성을 합산 초단위로 반환

print(diff.days, diff.seconds, diff.microsecond, diff.total_second())

# 현재로부터 365일이 지난 시점의 datetime을 알아봅시다

print("current:", current) # 현재의 시점이 나오죠

future = current + datetime.timedelta(day=365, seconds = 0, microseconds= 0)

print("future:", future)

네 이렇게 출력이 되네요^^

반응형
블로그 이미지

꽃꽂이하는개발자

,

Python datetime

2020/Python 2019. 11. 20. 19:10
반응형

#datetime은 날짜를 위한 date 객체, 시간을 위한 time 객체를 합친 것
#datetime 모듈을 import 사용

datetime은 날짜를 위한 date 객체, 시간을 위한 time 객체를 합친 것입니다.

datetime은 모듈을 import 하여 사용할 수 있습니다.

시간을 획득해 보도록 하겠습니다 현재시간의 datetime의 now() 메서드를 사용합니다.

dt = datetime.datetime.now()

print("now:",dt)

이렇게 출력됩니다.

 

# 특정 날짜와 시간을 얻을 때는 생성자를 활용하며 최소 년월일은 지정해야 합니다.

dt= datetime.datetime(1999,12,31)

print("dt:" dt)

#만약 실존하지 않는 날짜라면 ValueError이 뜨게 됩니다

dt = datetime.datetime(1999,12,32)

# 주요 속성들로는 year, month, day, hour, minute, second, microsecond를 얻을 수 있습니다.

print("dt의 연월일:", dt.year, dt.month, dt.day)

#요일의 확인 weekday() 메서드로 확인 합니다.

# 월요일은 0부터 시작하며 일요일은 6입니다.

print("1999-12-32일의 요일:" dt.weekday())

datetime에서 날짜만 확인하는 방법은 date() 를 사용하면 되며 date 객체를 반환합니다

마찬가지로 시간만 확인하는 것은 time() -> time 객체로 반환합니다.

 

 

 


import datetime #내장 객체

def get_datetime():
#시간의 획득
#현재 시간 datetime now() 메서드
dt = datetime.datetime.now()
print("now:", dt)

#특정 날짜와 시간을 얻을 때는 생성자를 활용
# 최소 년월일은 지정해야 한다
dt = datetime.datetime(1999,12,31)
print("dt:", dt)

#만약 실존하지 않는 날짜라면 ValueError
#dt = datetime.datetime(1999,12,32)

#주요 속성들로 year, month, day, hour, minute, second, microsecond를 얻을 수 있다.
print("dt의 연월일:", dt.year, dt.month, dt.day)

#요일의 확인 weekday() 메서드
# : 0~ : 6
print("1999-12-32일의 요일:", dt.weekday())

#datetime에서 날짜만 확인 date() -> date 객체 반환
#datetime에서 시간만 확인 time() ->time 객체 반환
nowdate = datetime.datetime.now().date()
nowtime = datetime.datetime.now().time()

print("NOWDATE:", nowdate, type(nowdate))
print("NOWTIME:", nowtime, type(nowtime))
#date 객체는 datetime이 가진 year, month, day 등 날짜 관련 속성들을 가지고 있다
#time 객체는 datetime이 가진 시간 관련 속성과 메서드들을 그대로 사용

반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형


def handling_exception():
""" 예외 처리 연습 """
# 인덱스 에러 IndexError
# 캐스팅 에러 ValueError
# 사전 키 접근 에러 KeyError
# 정수를 0으로 나눴을 경우 ZeroDivisionError

lst =[]
try:
#lst[3] =1 #IndexError
4/1 #ZeroDivisionError
#int("String") # valueError
except ValueError as e:
print("정수로 변환할 수 없어요.", e)
except ZeroDivisionError as e:
print("정수를 0으로 나눌 수 없어요.", e)
except IndexError as e:
print("인덱스 범위가 벗어났습니다.", e)
except Exception as e:
#Exception은 모든 예외의 부모 클래스
print("Exception:", e)
else:
print("예외없이 코드가 실행되었습니다.")

finally:
print("예외 여부 관계 없이 항상 마지막에 실행")

def raise_exception():
def beware_dog(animal):
if animal.lower() == "dog":
# 강제 익셉션 발생
raise RuntimeError("강아지는 출입을 제한합니다.")
else:
print("어서오세요!")
try:
beware_dog("cow")
beware_dog("cat")
beware_dog("dog")
except Exception as e:
print(e, type(e))

if __name__ =="__main__":
handling_exception()
raise_exception()

반응형
블로그 이미지

꽃꽂이하는개발자

,