혼공학습단/혼자 공부하는 파이썬

[혼공학습단 파이썬] 10기, 6주차 미션

✨️데이터분석가✨️ 2023. 8. 18. 08:00
728x90
728x90

혼공학습단 10기!
드디어 [혼자 공부하는 파이썬(개정판)]의 6주차 마지막 미션입니다.

 

파이썬 주차별 미션
파이썬 주차별 미션

 


6주차 - 기본 미션

[p431, 직접 해보는 손코딩: BeautifulSoup 스크레핑 실행하기] 예제 실행 후 결과 화면 캡처하기

- 기상청 홈페이지의 날씨 정보 스크레핑

from flask import Flask
from urllib import request
from bs4 import BeautifulSoup

app = Flask(__name__)
@app.route("/")

def hello():
    soup = BeautifulSoup(target, "html.parser")
    output = ""
    for location in soup.select("location"):
        output += "<h3>{}</h3>".format(location.select_one("city").string)
        output += "날씨: {}<br/>".format(location.select_one("wf").string)
        output += "최저/최고 기온: {}/{}".format(location.select_one("tmn").string, location.select_one("tmx").string)
        output += "<hr/>"
    return output

 

스크레핑 결과 화면
스크레핑 결과 화면

 

 

6주차 - 선택 미션

[객체, object]

- 속성을 가질 수 있는 모든 것

객체 지향 프로그래밍: 객체 관련 코드를 효율적으로 작성하는 프로그래밍 (예, class)

 

 

[클래스, class]

- 객체를 더 효율적으로 생성하기 위한 구문,

 

 

[인스턴스, instance]

- 클래스 기반으로 생성한 객체, 실체화 된 객체

 

 

[생성자, constructor]

- 클래스 이름과 같은 함수 (첫 문자는 대문자로 시작)

class 클래스 이름

    def __init__(self, 추가적인 매개변수...):

    self.매개변수 = 매개변수

  * self: 첫번째 매개변수, 자기자신을 나타내는 딕셔너리

 

 

[메소드, method]

- 클래스가 가진 함수

class 클래스 이름

    def 메소드 이름(self, 추가적인 매개변수...):

class Student:
    def __init__(selfnameage):     # → 생성자
        print("객체가 생성되었습니다.")
        self.name = name
        self.age = age
    def __del__(self):      # → 소멸자
        print("객체가 소멸되었습니다.")
    def output(self):       # → 메소드
        print(self.nameself.age)

student = Student("홍길동"20)
student.output()
# 실행결과
객체가 생성되었습니다.
홍길동 20
객체가 소멸되었습니다.

 

 

 

 

[혼공학습단 파이썬] #7-2. 외부 모듈(BeautifulSoup, Flask), 모듈 만들기, 디버깅

7. 모듈 2) 외부 모듈 (1) 모듈 설치하기 (2) BeautifulSoup 모듈 (3) Flask 모듈 (4) 라이브러리와 프레임워크 3) 모듈 만들기 4) 텍스트/바이너리 데이터 (1) 텍스트 데이터 (2) 바이너리 데이터 5) 디버깅 6)

dataslog.tistory.com

 

[혼공학습단 파이썬] #8-1. 클래스(인스턴스, 생성자, 메소드)

8. 클래스 1) 클래스 기본 (1) 객체 (2) 클래스 (3) 생성자 (4) 소멸자 (5) 메소드 2) 크기 비교 함수 1) 클래스 기본 (1) 객체 - 객체(object): 속성을 가질 수 있는 모든 것 - 객체 지향 프로그래밍: 객체 관

dataslog.tistory.com

 

[혼공학습단 파이썬] #8-2. 클래스 추가 기능(프라이빗 변수, 게터와 세터, 프로퍼티, 상속)

8. 클래스 3) 클래스 추가 기능 (1) 프라이빗 변수 (2) 게터와 세터 (3) 프로퍼티 (4) 상속 3) 클래스 추가 기능 (1) 프라이빗 변수 - 클래스 내부 변수를 외부에서 사용할 수 없는 변수 - __변수 이름 clas

dataslog.tistory.com

 

 

 

[외부 모듈]

외부 모듈: 파이썬이 기본으로 제공하지 않는 모듈 (사용자가 만든 모듈)

 

(1) 모듈 설치하기

- 명령 프롬포트에서 설치! (window+R → cmd 입력 or 터미널에서 입력)

- pip install 외부 모듈명

 

(2) BeautifulSoup 모듈

- 웹페이지 분석 모듈

- 기상청 홈페이지에서 날씨 확인하기

from urllib import request
from bs4 import BeautifulSoup
content = request.rulopen("http://www.weather.go.kr")
soup = BeautifulSoup(content, 'html.parser')
for data in soup.select("data"):
    print("시간:", data.select_one("tmef"))
    print("날씨:", data.select_one("wf"))
더보기

# 실행결과

시간: <tmef>2023-08-25 00:00</tmef>
날씨: <wf>흐림</wf>
시간: <tmef>2023-08-26 00:00</tmef>
날씨: <wf>흐림</wf>

...

 

 

(3) Flask 모듈

- 웹 개발 프레임워크 모듈

from flask import Flask
app = Flask(__name__)
@app.route("/")   # 데코레이터
def hello():
    return "Hello, World!"

 

- 실행은 명령 프롬포트에 아래 2줄 입력

> set FLASK_APP=파일명

> flask run

더보기

# 실행결과

* Serving Flask app 'flask_basic' (lazy loading)

...

 

 

(4) 라이브러리와 프레임워크

라이브러리, library 프레임워크, framework
정상적인 제어 방법으로 사용하는 모듈
(개발자가 모듈을 직접 사용)
제어 역전(IoC)이 일어나는 모듈
(모듈이 개발자의 코드를 사용)
* 제어 역전: 개발자가 만든 함수를 모듈이 실행하는 것
예) math 모듈 예) Flask 모듈

 

 

 

[모듈 만들기]

- 두 파일(실행 코드가 작성된 파일, 읽어들이는 main 파일)을 생성

# 파일명: module_test.py
print(__name__)
a = 10
b = 20
def c():
    return 30
if __name__ == "__main__":
    print("엔트리 포인트입니다. B")
더보기

# 실행결과

__main__
엔트리 포인트입니다. B

 

- 엔트리 포인트 = 메인: 프로그램의 진입점

- 모듈 내 __name__: 모듈명(파일명)을 의미

- __name__ == "__main__": 현재 파일이 엔트리포인트인지 확인

# 파일명: module_main.py
print(__name__)
import module_test as test
print(test.a)
print(test.b)
print(test.c())
if __name__ == "__main__":
    print("엔트리 포인트입니다. A")
더보기

# 실행결과

__main__
module_test    (→ 파일명 출력)
10
20
30
엔트리 포인트입니다. A

 

 

[텍스트/바이너리 데이터]

텍스트 데이터, text data 바이너리 데이터, binary data
텍스트 에디터에서 편집할 수 있는 데이터 텍스트 에디터로 편집할 수 없는 데이터
→ 전용 편집기 필요 (예, 포토샵 등)
용량이  용량이 작음

 

(1) 텍스트 데이터

- 텍스트 데이터는 편집 가능해서 기존과 동일하게 작성

file = open("output.py", "r")
print(file.read())
file.close()

 

 

(2) 바이너리 데이터

- 바이너리 데이터(이미지)는 편집 불가능이라 "rb", "wb"로 작성

  * read byte, write byte 

file = open("habit logo.png", "rb")
data = file.read()
print(data[:100])
file.close()
더보기

# 실행결과

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x07I\x00\x00\x05\x1a\x08\x06\x00\x00\x00\x80jK\xa1\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x002\xc0\x00\x002\xc0\x01(dZ\xdb\x00\x00\xff\xa5IDATx^\xec\x9d\x07\\\x14\xf7\xd6'

 

 

[클래스]

 

(1) 객체

- 객체(object): 속성을 가질 수 있는 모든 것

객체 지향 프로그래밍: 객체 관련 코드를 효율적으로 작성하는 프로그래밍 (예, class)

 

- 'students'가 객체이고, 딕셔너리를 아래와 같은 함수 형태로 생성하면 오타 등의 실수를 줄일 수 있음 

def input_student(name, korean, math, english):
    return{
        "name": name,
        "korean": korean,
        "math": math,
        "english": english
    }
def total(student):
    return student["korean"] + student["math"] + student["english"]
def average(student):
    return total(student) / 3
def output(student):
    print(student["name"], total(student), average(student), sep="\t")

students = [
    input_student("홍길동", 87, 68, 85),
    input_student("심청이", 97, 64, 73),
    input_student("김철수", 91, 75, 97),
    input_student("김영희", 70, 88, 84),
]

print("name", "total", "average", sep="\t")
for student in students:
    output(student)

 

 

(2) 클래스

- 클래스(class): 객체를 더 효율적으로 생성하기 위한 구문, 틀

- 인스턴스(instance): 클래스 기반으로 생성한 객체, 실체화 된 객체

 

 

(3) 생성자

- 클래스 이름과 같은 함수 (첫 문자는 대문자로 시작)

- class 클래스 이름

    def __init__(self, 추가적인 매개변수...):

    self.매개변수 = 매개변수

  * self: 첫번째 매개변수, 자기자신을 나타내는 딕셔너리

 

 

(4) 소멸자

- 인스턴스가 소멸될 때 호출되는 함수 (생성자 반대)

class 클래스 이름

    def __del__(self, 추가적인 매개변수...):

 

 

(5) 메소드

- 클래스가 가진 함수

- class 클래스 이름

    def 메소드 이름(self, 추가적인 매개변수...):

class Student:
    def __init__(self, name, age):     # → 생성자
        print("객체가 생성되었습니다.")
        self.name = name
        self.age = age
    def __del__(self):      # → 소멸자
        print("객체가 소멸되었습니다.")
    def output(self):       # → 메소드
        print(self.name, self.age)

student = Student("홍길동", 20)
student.output()

 

 

[크기 비교 함수]

eq ne gt ge lt le
equal not equal greater than greater than or equal less than less than or equal
같다 다르다 크다 크거나 같다 작다 작거나 같다
 

 

 

 

728x90
728x90