728x90

 

웹스크래핑 -> jupyter notebook사용 한줄한줄 확인하면서 작업해야 함

 


--모듈과 패키지 pip

 

-모듈이란?

  • 프로그램에서 작은 프로그램 조각들, 모듈들을 모아서 하나의 큰 프로그램을 개발한다.

  • 프로그램을 모듈화시키면 다른 프로그램에서 사용하기 쉽다.

  • 파이썬 모듈로 분리해서 프로그램 좀 더 구조화 할 수 있음

  • 파이썬의 Module == py 파일을 의미한다.

  • import문을 사용해서 Module을 호출한다.

 

-모듈을 import하는 4가지 방법

  1. 모듈명을 import하기

  2. 모듈명을 Alias 설정하기

  3. ⭐️모듈에서 특정 함수 또는 클래스만 import하기

  4. 모듈에서 모든 함수 또는 클래스를 import하기

# SoccerPlayer 클래스를 import
# from 패키지명.모듈명 import 클래스명 or 함수명
from mycode.oop.python_class import SoccerPlayer

 

--섭씨온도 화씨온도 변환

def transfer(n1):
    return ((9/5)*n1)+32
def sayHello(msg):
    return f'Hello {msg}!'
# 1. import 모듈명
# import exercise.fahrenheit
# 2. import 모듈명 as alias
# import exercise.fahrenheit as fah
# 3.from 모듈명 import 함수명
# from exercise.fahrenheit import transfer
# 4.from 모듈명 import *
from exercise.fahrenheit import *

print('변환하고 싶은 섭씨 온도를 입력해 주세요:')
n = float(input())

# 2번 모듈을 import한 경우
# answer = fah.transfer(n)

answer = transfer(n)
print('화씨 온도는', '%0.2f' % answer , '입니다.')
print(sayHello('파이썬'))

 

 

-빌트인 모듈 : 파이썬 설치 시 제공되는 내장 모듈

>>>import sys

>>>sys.path

>>>import random

>>>print (random.randint(0, 100)

 

-써드파티 모듈 : 외부 모듈로써 별도로 설치가 필요함

  • 파이썬 커뮤니티에 의해 지금도 계속 개발되고 배포되고 있음

 

-써드파티 모듈 설치 관리자 : pypi

  • 파이썬 모듈 중앙 저장소

  • https://pypi.python.org/pypi

  • 비교해 보기 : 자바 Maven Repository, 자바스크립트 NPM(node package manager) 저장소

 

 

# 외부 모듈 설치

pip install beautifulsoup4

#외부 모듈 설치 확인

pip show beautifulsoup4

Location: /Users/mhee4/opt/anaconda3/envs/jsEnv/lib/python3.8/site-packages

pip list

#외부 모듈 제거

pip uninstall beautifulsoup4

 


--예외처리

try:

예외 발생 가능 코드

except <Exception Type>:

예외 발생시 대응하는 코드

 

 

-Built-in Exception : 기본적으로 제공되는 예외.

https://docs.python.org/3/library/exceptions.html

 

try:

예외 발생 가능 코드

except <Exception Type>:

예외 발생시 동작하는 코드

else:

예외가 발생하지 않을 때 동작하는 코드

 

try:

예외 발생 가능 코드

except <Exception Type>:

예외 발생시 동작하는 코드

finally:

예외 발생 여부와 상관없이 실행됨

 

 

--raise구문 : 필요에 따라 강제로 Exception을 발생

raise <Exception Type>(예외정보)

for i in range(10):
    try:
        print(i, 10 // i)
    except ZeroDivisionError as err:
        print(err)
        print("Not divided by 0")

>>>integer division or modulo by zero

Not divided by 0

1 10

2 5

3 3

4 2

5 2

6 1

7 1

8 1

9 1

while True:
    value = input("변환할 정수값을 입력해주세요")
    for digit in value:
        if digit not in "0123456789":
            raise ValueError("숫자값을 입력하지 않으셨습니다")
    print("정수값으로 변환된 숫자 -", int(value))

 

--사용자 정의 예외 만들기

  • 새로운 예외 타입을 만들기 위해서는 class 객체 타입을 정의해야 한다.

# 사용자 정의 예외 클래스 선언
class NegativePriceException(Exception):
    # constructor 선언
    def __int__(self):
        print("Price can't be Negative")
        raise AttributeError
        
def calc_price(value):
    price = value * 100
    if price < 0:
        # NegativePriceException를 강제로 발생시킨다.
        raise NegativePriceException
    return price
    
print(calc_price(10))
print(calc_price(-10))

 


--파일 다루기

  • open() / close()로 파일 읽기

-r : read, w : write, a : append , rb : read binary, wb : write binary

  • ⭐️with 구문으로 파일 읽기

  • 한 줄씩 읽어 List Type으로 반환

# file open /read
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(f"Total Number of Characters {len(contents)}")
print(f'Total Number of Words {len(word_list)}')
print(f'Total NUmber of Lines {len(line_list)}')

>>>Total Number of Characters 9198

Total Number of Words 1656

Total NUmber of Lines 87

 

 


--웹스크래핑

 

데이터 수집(web scraping)과 분석(data science)

 

  1. requests (https://requests.readthedocs.io/en/master/)

: http 통신

: http Client의 역할

: python 기본 라이브러리 urllib 모듈

 

     2. beautifulsoup(https://www.crummy.com/software/BeautifulSoup/bs4/doc/)

: html, xml 형식의 Document Parsing(pulling data)

<a href="read.html"> Hello 파이썬 </a>

 

    3. Pandas

: Tablet(표) 데이터 분석, 데이터 가공, 처리

 

    4. Matplotlib, Seaborn

: 시각화

https://matplotlib.org/gallery/index.html

https://seaborn.pydata.org/

: ggplot, folium(지도), plotnine

 

    5. Pymysql, SqlAlchemy

: pymysql, sql - mysql(maria) DB 연동

: 썬이 마리아 디비를 인수합병한 후 썬을 오라클이 흡수함.

: sqlalchemy (ORM - object relational mapping) 쿼리문을 사용하지 않고 바로 사용할 수 있게 해줌

https://github.com/PyMySQL/PyMySQL

https://github.com/sqlalchemy/sqlalchemy/

 

 

**terminal창에

cd mypython webscrap_source

jupyter notebook

(chrome기본 브라우저로 설정해두어야함)

->jupyter notebook 띄우기

 

Jupyter notebook 단축키

cell 실행 : shift + enter

cell 주석 : ctrl + /

shift + tab : 함수 파라미터 확인 및 설명

h : 키보드 단축키 나옴

a : 위에 셀 생성

b : 아래 셀 생성

dd : 셀 삭제

m : 마크다운 모드

y : 코드 모드

j : 아래 셀로 이동

k : 위 셀로 이동

l : 코드 Line 표시

 

[출처] Python & Web Scraping (클라우드A반)|작성자 vega2k

 

 

  1. Nhn_News제목추출

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

url = 'https://news.naver.com/'
req_header = {
    'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
    }
res = requests.get(url, headers=req_header)
print(type(res))
print(res.status_code)
print(f'response header {res.headers}')
print(f'request header = {res.request.headers}')

#res.status_code == 200
if res.ok:
    #Response 객체에서 텍스트 추출
    html = res.text
    #print(html)
    soup = BeautifulSoup(html,'html.parser')
    #print(soup)
    atag_list = soup.select("a[href*='read.nhn']")
    print(type(atag_list), len(atag_list))
    #print(atag_list)
    for idx, atag in enumerate(atag_list, 1):
        title = atag.text.strip()
        link = urljoin(url, atag['href'])
        #print(f'{idx} => {title} {link}')
        print(idx, title, link)

 

   

    2. 파파고API사용

 

**네이버API사용 -> developers.naver.com/

# 네이버 Papago NMT API 예제

import os
import sys
import urllib.request
client_id = "y_8ZbXuSCA2hOCL42m6r"
client_secret = "Zwm47Ofq71"
encText = urllib.parse.quote("Yesterday all my troubles seemed so far away.")
data = "source=en&target=ko&text=" + encText
url = "https://openapi.naver.com/v1/papago/n2mt"
request = urllib.request.Request(url)
request.add_header("X-Naver-Client-Id",client_id)
request.add_header("X-Naver-Client-Secret",client_secret)
response = urllib.request.urlopen(request, data=data.encode("utf-8"))
rescode = response.getcode()
if(rescode==200):
    response_body = response.read()
    print(response_body.decode('utf-8'))
else:
    print("Error Code:" + rescode)

=>json형식 출력

 

>>>{"message":{"@type":"response","@service":"naverservice.nmt.proxy","@version":"1.0.0","result":{"srcLangType":"en","tarLangType":"ko","translatedText":"어제 나의 모든 걱정은 너무 멀리 있는 것 같다.","engineType":"N2MT","pivot":null}}}

 

 

  • requests 사용한 papago 예제

import requests

client_id = "y_8ZbXuSCA2hOCL42m6r"
client_secret = "Zwm47Ofq71"
url = "https://openapi.naver.com/v1/papago/n2mt"
enc_text = "Yesterday all my troubles seemed so far away."

req_header = {
    "X-Naver-Client-Id" : client_id,
    "X-Naver-Client-Secret" : client_secret
    }
req_param = {
    "source":"en",
    "target":"ko",
    "text":enc_text
    }
res = requests.post(url, data=req_param, headers=req_header)
print(res.ok, res.status_code)
print('요청 헤더 ', res.request.headers)
print('응답 헤더', res.headers)
if res.ok:
    print(res.text, type(res.text))
else:
    print('Http status code ', res.status_code)

>>>True 200

요청 헤더 {'User-Agent': 'python-requests/2.24.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'X-Naver-Client-Id': 'y_8ZbXuSCA2hOCL42m6r', 'X-Naver-Client-Secret': 'Zwm47Ofq71', 'Content-Length': '70', 'Content-Type': 'application/x-www-form-urlencoded'}

응답 헤더 {'Server': 'nginx', 'Date': 'Tue, 05 Jan 2021 07:35:10 GMT', 'Content-Type': 'application/json; charset=UTF-8', 'Content-Length': '230', 'Connection': 'keep-alive', 'Keep-Alive': 'timeout=5', 'X-QUOTA': '45', 'Content-Encoding': 'gzip'}

{"message":{"@type":"response","@service":"naverservice.nmt.proxy","@version":"1.0.0","result":{"srcLangType":"en","tarLangType":"ko","translatedText":"어제 나의 모든 걱정은 너무 멀리 있는 것 같다.","engineType":"N2MT","pivot":null}}} <class 'str'>

 

result_json = res.json()
print(result_json, type(result_json))
result_text = result_json['message']['result']['translatedText']
print(result_text)

 

>>>{'message': {'@type': 'response', '@service': 'naverservice.nmt.proxy', '@version': '1.0.0', 'result': {'srcLangType': 'en', 'tarLangType': 'ko', 'translatedText': '어제 나의 모든 걱정은 너무 멀리 있는 것 같다.', 'engineType': 'N2MT', 'pivot': None}}} <class 'dict'>

어제 나의 모든 걱정은 너무 멀리 있는 것 같다.

 

 

 

**Papago_yesterday번역하기

import requests

def translyric_savefile(trans_list):
    with open('data/yesterday_trans.txt','w',encoding='utf8') as file:
        file.writelines(trans_list)
        
#yesterday.txt 가사 파일의 내용을 읽어서 list에 저장
def gettext_savelist():
    lyric_list = []
    with open('data/yesterday.txt','r',encoding='utf8') as file:
        contents = file.read()
        lyric_list = contents.split('\n')
    return lyric_list
    
def main():
    client_id = "y_8ZbXuSCA2hOCL42m6r"
    client_secret = "Zwm47Ofq71"
    
    url = "https://openapi.naver.com/v1/papago/n2mt"
    
    #request header 값 선언
    req_header = {
        "X-Naver-Client-Id":client_id,
        "X-Naver-Client-Secret":client_secret
        }
    #yesterday.txt 가사 파일의 내용을 읽어서 list에 저장
    lyric_list = gettext_savelist()
    print(len(lyric_list))
    # list comprehension
    lyric_list = [lyric for lyric in lyric_list if len(lyric) != 0]
    print(len(lyric_list))
    
    trans_list = []
    print('>> 번역시작')
    for req_lyric in lyric_list:
        print(req_lyric)
        #request form data 값 선언
        req_data = {
            "source":"en",
            "target":"ko",
            "text":req_lyric
            }
        #papago 서비스 요청, post() 함수 호출
        res = requests.post(url, data=req_data, headers=req_header)
        
        try:
            trans_lyric = res.json()['message']['result']['translatedText']
        except Exception as exp:
            print(exp)
            print(res.status_code)
        else:
            print(trans_lyric)
            
        trans_list.append(req_lyric+'\n')
        trans_list.append(trans_lyric+'\n')
        
    translyric_savefile(trans_list)
    print('>> 번역 종료')
    
main()

>>>23

17

>> 번역시작

Yesterday all my troubles seemed so far away.

어제 나의 모든 걱정은 너무 멀리 있는 것 같다.

Now it looks as though they're here to stay.

이제 그들은 여기 머물려고 온 것처럼 보인다.

Oh, I believe in yesterday.

오, 나는 어제를 다시 그리게 돼.

Suddenly I'm not half the man I used to be.

갑자기 나는 예전보다 훨씬 더 작아졌다.

There's a shadow hanging over me.

그림자가 드리워져 있다

Oh, yesterday came suddenly.

아, 어제가 갑자기 다가왔어.

Why she had to go, I don't know, she wouldn't say.

왜 그녀가 가야 했는지는 모르겠지만 그녀는 말하지 않았다.

I said something wrong, now I long for yesterday.

내가 뭔가 잘못 말했는데, 이제 어제가 그리워.

Yesterday love was such an easy game to play.

어제는 사랑이 정말 쉬운 게임이었다.

Now I need a place to hide away.

이제 나는 숨을 곳이 필요해.

Oh, I believe in yesterday.

오, 나는 어제를 다시 그리게 돼.

Why she had to go, I don't know, she wouldn't say.

왜 그녀가 가야 했는지는 모르겠지만 그녀는 말하지 않았다.

I said something wrong, now I long for yesterday.

내가 뭔가 잘못 말했는데, 이제 어제가 그리워.

Yesterday love was such an easy game to play.

어제는 사랑이 정말 쉬운 게임이었다.

Now I need a place to hide away.

이제 나는 숨을 곳이 필요해.

Oh, I believe in yesterday.

오, 나는 어제를 다시 그리게 돼.

Mm mm mm mm mm mm mm

mm mm mm mm mm mm mm mm

>> 번역 종료

 

 

**웹툰이미지 다운받기

import requests
import os

req_header = {
    'referer' : 'https://comic.naver.com/webtoon/detail.nhn?titleId=703852&no=132&weekday=tue'
    }
    
img_url_list = [
    'https://image-comic.pstatic.net/webtoon/703852/132/20201221212625_b2bc8a16b5090eff701a39cf4b55310b_IMAG01_1.jpg',
    'https://image-comic.pstatic.net/webtoon/703852/132/20201221212625_b2bc8a16b5090eff701a39cf4b55310b_IMAG01_2.jpg',
    'https://image-comic.pstatic.net/webtoon/703852/132/20201221212625_b2bc8a16b5090eff701a39cf4b55310b_IMAG01_3.jpg'
    ]
for img_url in img_url_list:
    res = requests.get(img_url, headers=req_header)
    print(res.ok)
    if res.ok:
        # Response 객체에서 binary 데이터를 가져올때는 content 속성을 사용
        img_data = res.content
        file_name = os.path.basename(img_url)
        with open(file_name, 'wb') as file:
            print(f'Writing to {file_name} ({len(img_data)} bytes)')
            file.write(img_data)

>>>True

Writing to 20201221212625_b2bc8a16b5090eff701a39cf4b55310b_IMAG01_1.jpg (249235 bytes)

True

Writing to 20201221212625_b2bc8a16b5090eff701a39cf4b55310b_IMAG01_2.jpg (148417 bytes)

True

Writing to 20201221212625_b2bc8a16b5090eff701a39cf4b55310b_IMAG01_3.jpg (89124 bytes)

 

 

 

**과제

https://developers.naver.com/docs/nmt/reference/ 참고하여

파라미터로 파일을 받아서 번역하기

import requests

def translyric_savefile(trans_list, title):
    with open(f'data/{title}_trans.txt', 'w', encoding='utf8') as file:
        file.writelines(trans_list)
        
# yesterday.txt 가사 파일의 내용을 읽어서 list에 저장
def gettext_savelist(title):
    file_name = f'data/{title}.txt'
    lyric_list = []
    with open(file_name, 'r', encoding='utf8') as file:
        contents = file.read()
        lyric_list = contents.split('\n')
    return lyric_list
    
def main(title, source, target):
    client_id = "y_8ZbXuSCA2hOCL42m6r"
    client_secret = "Zwm47Ofq71"
    
    url = "https://openapi.naver.com/v1/papago/n2mt"
    
    # request header 값 선언 
    req_header = {
        "X-Naver-Client-Id": client_id,
        "X-Naver-Client-Secret": client_secret
        }
    # yesterday.txt 가사 파일의 내용을 읽어서 list에 저장 
    lyric_list = gettext_savelist(title)
    print(len(lyric_list))
    # list comprehension 
    lyric_list = [lyric for lyric in lyric_list if len(lyric) != 0]
    print(len(lyric_list))
    
    trans_list = []
    print('>> 번역시작')
    for req_lyric in lyric_list:
        print(req_lyric)
        # request form data 값 선언 
        req_data = {
            "source": source, 
            "target": target, 
            "text": req_lyric
            }
        # papago 서비스 요청, post() 함수 호출 
        res = requests.post(url, data=req_data, headers=req_header)
        
        try:
            trans_lyric = res.json()['message']['result']['translatedText']
        except Exception as exp:
            print(exp)
            print(res.status_code)
        else:
            print(trans_lyric)
            
        trans_list.append(req_lyric + '\n')
        trans_list.append(trans_lyric + '\n')
        # print(trans_list) 
        
    translyric_savefile(trans_list, title)
    print('>> 번역 종료')
    
main('shallow', 'en', 'ko')

 

 

 

728x90

+ Recent posts