본문 바로가기
study/Python

[Python] 33. 클래스에서 사용되는 특별한 함수들, 모듈, 정규식, 파일 읽고 쓰기

by 금이패런츠 2022. 6. 16.
728x90
반응형

1. 클래스에서 사용되는 특별한 함수들

2. 모듈 : import 모듈명.

3. 정규식

4. 파일 읽기, 쓰기

# -*- coding: utf-8 -*-
"""
Created on Thu Jun 16 08:48:12 2022

@author: p011v
"""

'''
    함수 : def 예약어로 함수 정의
            return 값 : 함수를 종료하고 값을 전달
            매개변수 : 함수를 호출할 때 필요한 인자값 정의
                가변매개변수 : 매개변수의 갯수를 지정안함. 0개 이상. * p 표현
                기본값설정 : (n1=0, n2=0) :0, 1, 2개의 매개변수 가능 
                
    예외처리 : try, except, finally, else, raise   

    클래스 : 멤버변수, 멤버함수, 생성자.
            인스턴스변수 : self.변수명. 객체 별로 할당되는 변수
            클래스변수 : 클래스명.변수명. 모든 객체의 공통변수
    self : 자기참조변수. 인스턴스함수에 첫번째 매개변수로 설정.
    생성자 : __init__(self,...) : 객체생성에 관여하는 함수
            클래스내부에 생성자가 없으면 기본생성자를 제공.
    상속 : class 클래스명 (부모클래스명1, 부모클래스명2,...) : 다중상속가능
        오버라이딩 : 부모클래스의 함수를 자손클래스가 재정의
'''

########## 1. 클래스에서 사용되는 특별한 함수들
'''
클래스에서 사용되는 연산자에 사용되는 특수 함수
+   __add__(self, other)
–	__sub__(self, other)
*	__mul__(self, other)
/	__truediv__(self, other)
//	__floordiv__(self, other)

%	__mod__(self, other)

**	__pow__(self, other)

&	__and__(self, other)
|	__or__(self, other)
^	__xor__(self, other)

<	__lt__(self, other)
>	__gt__(self, other)
<=	__le__(self, other)
>=	__ge__(self, other)
==	__eq__(self, other)
!=	__ne__(self, other)


생성자 : __init__(self,...) : 클래스 객체 생성시 요구되는 매개변수에 맞도록 매개변수 구현
출력   : __repr__(self) : 클래스의 객체를 출력할때 문자열로 리턴.
'''

class Line : 
    length = 0
    def __init__(self,length) : #생성자
        self.length = length
    def __repr__(self) :        #객체를 문자열화
        return "선길이: " + str(self.length)
    def __add__(self,other) : # + 연산자 자용시 호출
        print("+ 연산자 사용 : ", end="")
        return self.length + other.length
    def __lt__(self,other):     # < 연산자 자용시 호출
        print("< 연산자 호출 : ")
        return self.length < other.length
    def __gt__(self,other):     # > 연산자 자용시 호출
        print("> 연산자 호출 : ")
        return self.length > other.length
    def __eq__(self,other):     # == 연산자 자용시 호출
        print("== 연산자 호출 : ")
        return self.length == other.length
   
line1 = Line(200)
line2 = Line(100)
print("line1=", line1) #__repr__(self) : 객체를 문자열화
print("line2=", line2)
print("두선의 합 : ", line1 + line2)
print("두선의 합 : ", line1.__add__(line2))
# 크기비교 : 
# <  : __lt__(self,other)
# >  : __gt__(self,other)
# == : __eq__(self,other)

if line1 < line2 :
    print("line2선이 더 깁니다.")
elif line1 == line2 :
    print("line1선과 line2선의 길이는 같습니다.")
elif line1 > line2 :
    print("line1선이 더 깁니다.")


'''
    추상함수 : 오버라이딩을 강제화시키는 함수
              함수의 구현부에 raise NotImplementedError 기술함
'''

class Parent :
    def method(self) : #추상함수
        raise NotImplementedError
        
class Child(Parent) :
    def method(self) :
        print("자손클래스에서 오버라이딩 함")
ch = Child()
ch.method()

########## 2. 모듈 : import 모듈명.
#mod1.py, mod2.py 파일의 함수를 호출하기
import mod1 #mod1.py 파일의 내용을 가져옴
import mod2 #mod2.py 파일의 내용을 가져옴
print("mod1 모듈 add()=", mod1.add(40,30))
print("mod1 모듈 sub()=", mod1.sub(40,30))
print("mod2 모듈 add()=", mod2.add(40,30))
print("mod2 모듈 sub()=", mod2.sub(40,30))

import mod1 as m1 #mod1 모듈의 별명 설정
import mod2 as m2
print("mod1 모듈 add()=", m1.add(40,30))
print("mod1 모듈 sub()=", m1.sub(40,30))
print("mod2 모듈 add()=", m2.add(40,30))
print("mod2 모듈 sub()=", m2.sub(40,30))

#import 되는 다른 모듈의 함수이름이 같은 경우 주의 요망
# 어떤 모듈의 함수인지 판단해야 함
from mod1 import add,sub #mod1의 함수만 import
from mod2 import add    
print(add(100,200))
print(sub(200,200))

import mod1 #mod1.py 파일의 내용을 가져옴
import mod2 #mod2.py 파일의 내용을 가져옴
# dir(mod1) : mod1 모듈의 기본으로 제공되는 변수 조회할 수 있는 함수
print("mod1: ", dir(mod1)) #기본변수 조회
print("mod2: ", dir(mod2)) #기본변수 조회

print("__name__:", __name__) #__main__
print("mod2.__name__:", mod2.__name__) #mod2

# 주민번호 감추기
data = '''
        park 800995-1234567
        kim 890125-2345678
        choi 850125-a123456
        '''
print(data)

result=[]
#line :  park 809095-1234567
for line in data.split("\n") :
    word_result = [] #park 
    # word : park
    for word in line.split(" ") :
        if len(word) == 14 and word[:6].isdigit() and word[7:].isdigit() :
            word = word[:6] + "-" + "*******"
        word_result.append(word)
    result.append(" ".join(word_result))
print("\n".join(result))

########## 3. 정규식
# 정규식을 이용하여 주민번호 감추기
import re #정규식 이용을 위한 모듈. 이름이 re 임..
data = '''
        park 800995-1234567
        kim 890125-2345678
        choi 850125-a123456
        '''
# re.compile("패턴")
# pat : 패턴객체. re.compile 설정된 정규식 형태 저장객체
# (\\d{6,7})[-]\\d{7} : 첫번째 그룹은 숫자가 6,7자리, -, 숫자 7자리로 이루어진 문자열
# () : 그룹
# \d{6,7} : 6,7자리 숫자형태
# [] : 문자. [-] : - 문자
# \d{7} : 7자리 숫자형태
pat = re.compile("(\\d{6,7})[-]\\d{7}")
# pat.sub : 패턴을 찾아서 문자열 변경하기
# pat.sub(변경형태, 문자열)
# data 값에서 pat에 맞는 부분을 \g<1>-******* 형태로 변경
'''
    park 800995-1234567
    kim 890125-2345678
    choi 850125-a123456
'''
# \g<1> : 첫번째 그룹
print(pat.sub("\g<1>-*******", data)) 

#정규식을 이용하여 데이터 찾기
str1 = "The quick brown fox jumps over the laze dog Te THE"
str_list = str1.split() #공백을 기준으로 분리
print(str_list)
# * : 0개 이상
pattern = re.compile("Th*e") # T문자로 시작하고, e로 끝나는 문자열. 중간 h문자가 있거나 없거나
count = 0
for word in str_list :
    if pattern.search(word) : #The, Te / the는 소문자라서 포함안됨
        count += 1
print("결과1:{0:s}:{1:d}".format("갯수", count))

pattern = re.compile("Th*e",re.I) #re.I : 대소문자 구분없이
count = 0
for word in str_list :
    if pattern.search(word) : #The, the, Te, THE
        count += 1
print("결과2:{0:s}:{1:d}".format("갯수", count))

#결과2에 맞는 문자열 출력하기
print("결과3: ", end="")
for word in str_list :
    if pattern.search(word) : #The, the, Te, THE
        print(word, end=",")
print()

#결과2에 맞는 문자열 출력하기
#findall(패턴, 문자열) : 문자열 내부에서 패턴에 맞는 문자열 리스트 리턴
print("결과4: ", re.findall(pattern, str1))

#결과2에 맞는 문자열의 갯수 출력하기
print("결과5: ", len(re.findall(pattern, str1)))

#결과2에 맞는 문자열을 aaa로 변경하기
# aaa quick brown fox jumps over aaa laze dog aaa aaa
print("결과6: ",pattern.sub('aaa', str1))

# 문제
# str2 문자열에서 온도의 평균 출력하기
str2 = "서울:25도,부산:23도,대구:27도,광주:26도,대전:25도,세종:27도"

pattern = re.compile("\\d{2}") #2자리의 숫자형태 찾기 pattern변수 만들기기
list1 = re.findall(pattern, str2) #str2문자열 내부에서 2자리숫자형태 패턴 문자열 list1에 리스트
print(list1)
list1 = list(map(int,list1)) #list1 리스트 문자열 int 값으로 변경
print(list1)
print(sum(list1)/len(list1)) #list1 더하고 len(자릿수)로 나누기

'''
정규식
정규식에서 사용되는 기호
1. () : 그룹. 설정
2. \g<n> : n번째 그룹 조회.
3. [] : 문자
   [a] : a문자
   [a-z] : 소문자
   [A-Za-z] : 영문자
   [0-9A-Za-z] : 영문자+숫자
4. {n} : n개.갯수
      ca{2}t : a문자가 2개
      ct : false
      cat : false
      caat : true
      caaat: false
  {n,m} : n이상 m개 이하 갯수
      ca{2,5}t : a 문자가 2개이상 5개이하
        ct : false
        cat : false
        caat : true
        caaat: true
5. \d : 숫자.
6. ? : 0 또는 1
    ca?t : a문자는 없거나, 1개만 가능
     "ct" : true
     "cat" : true
     "caat" : false
7. * : 0개이상
    ca*t : a문자는 0개이상
    "ct" : true
    "cat" : true
    "caat" : true
 8. + : 1개이상
    ca+t : a문자는 1개이상
    "ct" : false
    "cat" : true
    "caat" : true
9. \s : 공백
   \s+ : 공백문자 1개이상.
'''

########## 4. 파일
'''
    open("파일명", 파일모드, [인코딩])
    인코딩 : 파일의 저장방식 지정. 기본값:cp949형식
    파일모드 : 
        r : 읽기
        w : 쓰기. 기존파일은 무시하고 새로운 파일 생성
        a : 쓰기. append 모드. 기존의 파일의 내용에 추가
        t : text 모드. 기본값. 생략가능
        b : 이진모드. binary모드. 이미지, 동영상, 음성 등 text파일 외...
    
'''
# 읽기
infp = open("test0615.py", "rt", encoding="UTF-8")
while True :
    instr = infp.readline()
    if instr == None or instr == '' :
        break
    print(instr, end="")
infp.close()

# 쓰기
# 콘솔에서 내용을 입력받아 파일로 생성하기
outfp = open("data.txt", "w", encoding="UTF-8")
while True :
    outstr = input("내용입력=>")
    if outstr == '' :
        break;
    outfp.writelines(outstr+"\n") #writelines : 한줄씩 입력
outfp.close()

#data.txt 파일을 읽어서 화면에 출력하기
infp2 = open("data.txt", "rt", encoding="UTF-8")
while True :
    instr2 = infp2.readline()
    if instr2 == None or instr2 == '' :
        break
    print(instr2, end="")
infp2.close()
'''
    readline()  : 한줄씩 읽기
    read()      : 한번에 읽기
    readlines() : 한줄씩 읽어서 여러줄을 리스트로 저장장
'''
infp2 = open("data.txt", "rt", encoding="UTF-8")
print(infp2.read())
infp2.close()

infp2 = open("data.txt", "rt", encoding="UTF-8")
print(infp2.readlines())
infp2.close()

#이미지파일 읽기
#apple.gif 파일을 읽어, apple2.gif 파일로 저장하기
infp3 = open("apple.gif", "rb") #원본파일
outfp3 = open("apple2.gif", "wb") #복사본파일
while True :
    indata = infp3.read() #설정된 버퍼의 크기만큼 읽기
    if not indata : #EOF (End Of File) : 파일의 끝
        break
    outfp3.write(indata) #버퍼의 내용을 파일에 쓰기
infp3.close()
outfp3.close()

# 문제 : score.txt 파일을 읽어서 점수의 총점과 평균 구하기
import re
infp = open("score.txt", "r", encoding="UTF-8")
instr = infp.read()
print(instr)
#\\d+ : \d : 숫자, +:1개이상
pattern = re.compile("\\d+")
list1 = re.findall(pattern, instr)
print(list1)
list1 = list(map(int, list1))
print("총합: ", sum(list1), "평균: ", sum(list1)/len(list1))

# -*- coding: utf-8 -*-
"""
Created on Thu Jun 16 10:43:30 2022

@author: p011v
mod1.py
"""
def add(a,b) :
    print("mod1")
    return a+b

def sub(a,b) :
    print("mod1")
    return a-b

# -*- coding: utf-8 -*-
"""
Created on Thu Jun 16 10:47:00 2022

@author: p011v
mod2.py
"""
def add(a,b) :
    print("mod2")
    return a+b
def sub(a,b) :
    print("mod2")
    return a-b

# mod2.py 직접 호출되는 경우만 실행되도록 조건 설정
# mod2.py 직접 실행해야만 __main__. 즉, import 되는 경우는 실행되지 않도록 설정함
# 프로그램의 시작. 
if __name__=='__main__' :
    print("mod2.py 실행됨")
    print("add(3,4)=", add(3,4))
    print("sub(4,2)=", sub(4,2))

score.txt
0.00MB

728x90
반응형

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

[Python] 33. Test 답  (0) 2022.06.16
[Python] 33. Test  (0) 2022.06.16
[Python] 32. Test  (0) 2022.06.15
[Python] 32. 함수와 람다, 변수, 예외처리, 클래스  (0) 2022.06.15
[Python] 31. Test 답  (0) 2022.06.14