반응형
반응형
# 본 프로그램은 텍스트 데이터를 빈도 분석하기 전 기초편입니다.
# 작성자 이성재
# 프로그램 wc_base02.py
# import 와 from의 차이를 구분해서 사용할 수 있게한다.
# Counter를 사용하면 출력 결과는 Dictionary 형태로 반환하여 준다.

from collections import Counter
import collections

List = ['aa','dd','cc','aa','bb','ee']

# from collections import Counter 을 사용 했을 때
dict1 = Counter(List)
print (dict1)
# 출력 : Counter({'aa': 2, 'dd': 1, 'cc': 1, 'bb': 1, 'ee': 1})

# most_common() 은 딕셔너리 형태를 배열로 변환
dict1_arry = dict1.most_common() # most_common() 배열로 변환하는 함수
print(dict1_arry)
# 출력 : [('aa', 2), ('dd', 1), ('cc', 1), ('bb', 1), ('ee', 1)]

# dict함수는 배열형태로 되어있는 딕셔너리형 데이터를 다시 딕셔너리형으로 변경
new_dict1 = dict(dict1_arry) # dict 배열형태로 변환
print(new_dict1)
# 출력 : {'aa': 2, 'dd': 1, 'cc': 1, 'bb': 1, 'ee': 1}

Counter메소드를 사용할 경우 배열 같은 요소의 갯수를 세어줍니다.

most_common()메소드는 사전형 요소를 튜플로 만들고 리스트로 담습니다.

 

 

반응형

'파이썬' 카테고리의 다른 글

파이썬 파일 (txt)  (0) 2021.07.20
파이썬 전역변수 지역변수  (0) 2021.07.20
파이썬 메소드 만들기  (0) 2021.07.20
파이썬 추상클래스  (0) 2021.07.20
파이썬 다중상속  (0) 2021.07.20
반응형

 

# ------------------ 파일 입력하기 ------------------

s = """
Hello World!
"""

f = open('t.txt', 'w')
print(f.write(s))  # 출력 : 14
f.close()

with open('t1.txt', 'w') as f:
    f.write('위대한 세종대왕')


lines = ['first line\n', 'second line\n', 'third line\n']
f = open('t3.txt', 'w')
f.writelines(lines)  


with open('t3.txt') as f:
    for line in f:
        print(line, end='')

"""
출력 : 
first line
second line
third line
"""

# ------------------ 파일 내용 출력 ------------------

f = open('t.txt')
s = f.read() 
print(s)  # 출력 : Hello World!
f.close()

print(open('t.txt').read())  # 출력 : Hello World!

with open('t.txt') as f:
    print(f.read())  # 출력 : Hello World!


# ------------------ 이어적기 ------------------


f = open('remove.txt', 'w')
f.write('first line\n')

f.write('second line\n')
f.close()

f = open('remove.txt', 'a')  
f.write('third line\n')
f.close()

f = open('remove.txt')
print(f.read())
f.close()

"""
출력 : 
first line
second line
third line
"""

f = open('t.txt', 'w')
print(f.write(s)) # 출력 : 14
f.close()

 

f = open('텍스트명' , '모드')

'텍스트명'여는 작업입니다. 모드읽기모드(r) 쓰기모드(w) 이어쓰기모드(a)가 있습니다.

쓰기모드로 들어왔을 때 f.write(쓸 내용)으로 텍스트명에다 내용을 적는 과정입니다.

그리고 f.close()를 통해서 연 것을 닫아줘야합니다.

 

with open('t1.txt', 'w') as f:
    f.write('위대한 세종대왕')

 

with open('텍스트명' , '모드') as f

이렇게 열수도 있습니다. 위와 다른 점은 이렇게 열면 f.close()를 자동적으로 해줍니다.

 

f.writelines(컨테이너객체)

writelines\n을 기준으로 줄바꿈해서 저장해줍니다.

컨테이너객체가 들어간다 안 들어간다 이렇게 외우면 머리 아프니까 이해하면 편합니다.

\n이 들어가야 줄바꿈을 하니까 정수형이나 실수형은 \n가 들어갈 수도 없잖아요?

 

f = open('t.txt')
s = f.read()
print(s) # 출력 : Hello World!
f.close()

 

아무것도 안 적은 건 읽기모드입니다.

f = open('t.txt', 'r') 이렇게 쓸 수도 있습니다.

내용을 출력하려면 f.read()를 print문으로 출력해야합니다.

 

1. print(open('t.txt').read()) # 출력 : Hello World!

2. with open('t.txt') as f:
       print(f.read()) # 출력 : Hello World!

 

이런식으로 한번에 출력할 수도 있습니다.

 

f = open('remove.txt', 'a')

이건 이어적기모드입니다. 만들어진 텍스트파일에 이어적을 때 쓰는 모드입니다.

w를 쓰면 전에 적혔던 내용들 다 날라가고 새로 작성이 됩니다.

반응형

'파이썬' 카테고리의 다른 글

파이썬 Counter, most_common 메소드  (0) 2021.07.23
파이썬 전역변수 지역변수  (0) 2021.07.20
파이썬 메소드 만들기  (0) 2021.07.20
파이썬 추상클래스  (0) 2021.07.20
파이썬 다중상속  (0) 2021.07.20
반응형
def A() :
    return
print(A()) # 출력 : None

def B() :
    pass
print(B()) # 출력 : None

a = 20
def f(a):
    a = 10
f(a)
print(a) # 출력 : a = 20

def g(t):
    t[1] = 10
a = [1, 2, 3]
g(a)
print(a) # 출력 : [1, 10, 3]

def gg(t) :
    t = [1, 2, 3]
a = [5, 6, 7]
gg(a)
print(a) # 출력 : [5, 6, 7]

def f(a):
   a = 10

이렇게 a를 매개변수로 받아 지역에서 처리해줘도 a의 값은 변하지 않습니다.

gg() 메소드도 변하지 않은 걸 알 수 있습니다.

 

def g(t):
    t[1] = 10

하지만 인덱스로 접근해서 값을 변경한 경우는 값이 바뀝니다.

 

반응형

'파이썬' 카테고리의 다른 글

파이썬 Counter, most_common 메소드  (0) 2021.07.23
파이썬 파일 (txt)  (0) 2021.07.20
파이썬 메소드 만들기  (0) 2021.07.20
파이썬 추상클래스  (0) 2021.07.20
파이썬 다중상속  (0) 2021.07.20
반응형
def add (a,b):
    return a + b

print(add(3,4)) # 출력 : 7
print(add([1,2,3],[4,5,6])) # 출력 : [1, 2, 3, 4, 5, 6]
print(add(a = 10 , b = 5)) # 출력 : 15

def plus (a , b = 1 ) :
    return a + b

print(plus(3)) # 출력 : 4
print(plus(4,5)) # 출력 : 9

def area(h , w) :
    return h * w

print(area(w = 20 , h = 10)) # 출력 : 200
print(area(20,w = 5)) # 출력 : 100
# print(area(h = 5 , 20)) # 인수 이후 값이 나오면 에러

def 메소드명 (매개변수...) :

    return 리턴값

 

def plus (a , b = 1 ) :

print(plus(3)) # 출력 : 4

 

이거처럼 매개변수를 두개 받는데 한 개를 받을 때 b = 1 이라고 적은 인자값이 기본 값이 되어

print(plus(3,1))같은 역할을 합니다.

 

print(area(w = 20 , h = 10)) # 출력 : 200

또한 이거 처럼 매개변수 적는 곳에 적을 수도 있습니다. 

하지만 인수 이후값이 나오면 에러가 나옵니다.

반응형

'파이썬' 카테고리의 다른 글

파이썬 파일 (txt)  (0) 2021.07.20
파이썬 전역변수 지역변수  (0) 2021.07.20
파이썬 추상클래스  (0) 2021.07.20
파이썬 다중상속  (0) 2021.07.20
파이썬 상속  (0) 2021.07.20
반응형
class Animal:
    def cry(self):
        print('...')

class Dog(Animal):
    def cry(self):
        print('멍멍')

class Duck(Animal):
    def cry(self):
        print('꽥꽥')

class Fish(Animal):
    pass

for each in (Dog( ),Duck(),Fish( )):
    each.cry() # 출력 : 멍멍 꽥꽥 ...

추상클래스를 만드는 법은 상속받아서 그냥 거기서 정의한 메소드를 덮어 씌우시면 됩니다.

반응형

'파이썬' 카테고리의 다른 글

파이썬 전역변수 지역변수  (0) 2021.07.20
파이썬 메소드 만들기  (0) 2021.07.20
파이썬 다중상속  (0) 2021.07.20
파이썬 상속  (0) 2021.07.20
파이썬 클래스  (0) 2021.07.20
반응형
class Person:
    def __init__(self, name, phone = None):
        self.name = name
        self.phone = phone
    def __repr__(self):
        return ' name = {} , tel = {}'.format(self.name,self.phone)

class Job:
    def __init__(self,position,salary):
        self.position = position
        self.salary = salary
    def __repr__(self):
        return 'position = {} salary = {}'.format(self.position,self.salary)

class Employee(Person,Job):
    def __init__(self,name,phone,position,salary):
        Person.__init__(self,name,phone)
        Job.__init__(self,position,salary)
    def raisesalary(self,rate):
        self.salary = self.salary * rate
    def __repr__(self):
        return Person.__repr__(self) + ' ' + Job.__repr__(self)
e = Employee('gslee',5244,'prof',300)
e.raisesalary(1.5)
print(e) # 출력 : name = gslee , tel = 5244 position = prof salary = 450.0

파이썬은 다중상속이 됩니다.

자바의 경우는 클래스 상속이 한 개만 가능했는데 여기선 이걸 가능하게 만들어버리네요

다중 상속법은 간단합니다. 

class Employee(Person,Job)

이와 같이 괄호 안에 상속받을 두개의 클래스를 적으면 됩니다.

 

하지만 여기서 super().__init__이나 __repr__은 사용하지 못합니다.

super에 해당하는게 Job과 Perosn으로 두개이기 때문이죠 겹치지만 않는다면 상관 없다고 생각합니다만

반응형

'파이썬' 카테고리의 다른 글

파이썬 메소드 만들기  (0) 2021.07.20
파이썬 추상클래스  (0) 2021.07.20
파이썬 상속  (0) 2021.07.20
파이썬 클래스  (0) 2021.07.20
파이썬 map, filter , lambda  (0) 2021.07.20
반응형
class Person:
    def __init__(self, name, phone=None):
        self.name = name
        self.phone = phone

    def __repr__(self):
        return '<Person {} {}>'.format(self.name, self.phone)

class Employee(Person):
    def __init__(self, name, phone, position, salary):
        Person.__init__(self, name, phone)  
        self.position = position
        self.salary = salary


class Employee2(Person):
    def __init__(self, name, phone, position, salary):
        super().__init__(name, phone) 
        self.position = position
        self.salary = salary

    def __repr__(self): 
        return '<Person {} {} {} {}>'.format(self.name, self.phone, self.position, self.salary)


m1 = Employee('손창희', 5565, '대리', 200)
print(m1)  # 출력 : <Person 손창희 5565>
m2 = Employee2('손창희', 5565, '대리', 200)
print(m2) # 출력 : <Person 손창희 5565 대리 200>

Person이라는 클래스를 만들어줬습니다.

 

def __repr__(self):
     return '<Person {} {}>'.format(self.name, self.phone)

__repr__ 이것의 기능은 print문으로 객체찍으면 출력되는 문장입니다. 

여기에선 이름과 전화번호가 출력되겠네요

 

class Employee2(Person)

상속을 받으려면 self대신 상위 클래스를 괄호안에 적어주시면 됩니다.

생성자에 공통 부분Person.__init__(self, name, phone) 이런식으로 재활용이 가능합니다.

 

super().__init__(name, phone) 이것을 쓸 수도 있습니다.

class Person:
    def __init__(self, name, phone=None):
        self.name = name
        self.phone = phone

    def __repr__(self):
        return '<Person {} {}>'.format(self.name, self.phone)


class Employee(Person):
    def __init__(self, name, phone, position, salary):
        super().__init__(name, phone)
        self.position = position
        self.salary = salary

    def __repr__(self):
        s = super().__repr__()
        return s + '<Person {} {}>'.format(self.position, self.salary)


m1 = Employee('손창희', 5565, '대리', 200)
print(m1)  # 출력 : <Person 손창희 5565><Person 대리 200>

이런식으로 s = super().__repr__() 와 같이 __repr__도 super() 사용이 가능합니다.

반응형

'파이썬' 카테고리의 다른 글

파이썬 추상클래스  (0) 2021.07.20
파이썬 다중상속  (0) 2021.07.20
파이썬 클래스  (0) 2021.07.20
파이썬 map, filter , lambda  (0) 2021.07.20
파이썬 Try except finally  (0) 2021.07.18
반응형
class MyClass3:
    def __init__(self):
        self.value = 0

    def get(self):
        return self.value


c = MyClass3()
c.get()  # 출력 : 0


class MyClass4:
    def __init__(self, name, nic, birthday):
        self.name = name
        self.nick = nic
        self.birthday = birthday

m1 = MyClass4('이열', '해안선', '1995-4-3')

 

클래스에 대한 설명은 자바에 했으니 그냥 넘어가겠습니다.

 

class 클래스명 :

     내용....

 

이런식으로 클래스를 선언할 수 있습니다.

 

__init__이란 생성자역할을 해줍니다. 클래스를 선언하면 바로 들어갈 값인거죠

파이썬 클래스는 특이하게 (self)가 들어가야합니다. 또한 클래스 변수를 선언할 필요가 없습니다.

 

c = MyClass3()
c.get() # 출력 : 0
self.value = 0으로 생성자를 했기 때문에 value 값에 0 이 들어가 0이 출력되는 것 입니다.

그리고 클래스 변수에 접근하려면 self 를 이용해야합니다. this와 비슷하다고 생각하시면 좋을 거 같네요

 

생성자초기 변수 값을 선언할 수 있는 거 처럼 만들 수도 있습니다

__init__(self, name, nic, birthday

m1 = MyClass4('이열', '해안선', '1995-4-3')

name = 이열 , nic = 해안선 , birthday = 1995-4-3가 들어가게 되는 것입니다.

반응형

'파이썬' 카테고리의 다른 글

파이썬 다중상속  (0) 2021.07.20
파이썬 상속  (0) 2021.07.20
파이썬 map, filter , lambda  (0) 2021.07.20
파이썬 Try except finally  (0) 2021.07.18
파이썬 Math 관련 함수  (0) 2021.07.18
반응형

 

def f(x):
    return x * x

X = [1,2,3,4,5]

list(map(f,X)) # 출력 : [1,4,9,16,25]

Y =  list(map(lambda a : a * a, X))  # 출력 : 출력 : [1,4,9,16,25]

P = [1,2,3,4,5]
Q = [6,7,8,9,10]

Z = list(map(lambda x , y : x + y ,P, Q)) # 출력 : [7,9,11,13,15]


# ------------------- filter ---------------------------

f = filter(lambda x : x + 2 , [1,2,3,4])
print(list (f)) # 출력 : [1 ,2 ,3 ,4]

 

map(적용할 함수, 적용시킬 대상)

컨테이너객체에 있는 요소들을 하나씩 적용할 함수를 적용시킵니다.

X = [1,2,3,4,5]

list(map(f,X)) # 출력 : [1,4,9,16,25]

여기에서 f라는 함수X라는 리스트에 하나씩 적용시켰기 때문에 이렇게 나오게 됩니다.

 

lambda라는것이 있는데 이것도 함수를 만들어 줍니다.

lambda 인자값 : 리턴값 , 적용시킬 것 이러한 구조입니다.

 

Z = list(map(lambda x , y : x + y ,P, Q)) # 출력 : [7,9,11,13,15]

x, y를 인자값으로 받아 x + y를 한 것을 출력합니다. 매개변수는 P, Q입니다.

 

이와 비슷한 기능을하는게 filter함수입니다.

filter(적용할 함수, 적용시킬 대상)

 

그와 다르게 filter 함수는 함수를 사용해도 참 거짓구분하지 map처럼 적용시켜 바뀌는 건 아닙니다.

반응형

'파이썬' 카테고리의 다른 글

파이썬 상속  (0) 2021.07.20
파이썬 클래스  (0) 2021.07.20
파이썬 Try except finally  (0) 2021.07.18
파이썬 Math 관련 함수  (0) 2021.07.18
파이썬 이중for문  (0) 2021.07.18