Python 21

[Python] 순열 만들기

리스트 원소로 조합할 수 있는 모든 순열 구하기 예제코드import itertools y = [i for i in range(3)] # [0, 1, 2] y_permuatation = itertools.permutations(y, 3) itertools의 permutations()를 이용하면 간단히 만들 수 있다 for yp in y_permuatation: print(yp) (0, 1, 2) (0, 2, 1) (1, 0, 2) (1, 2, 0) (2, 0, 1) (2, 1, 0)y_permutaion의 값들을 꺼내보면 순열이 만들어져있음을 볼 수 있다 itertools.permutations() 사용법itertools.permutations(리스트, 순열의 길이) 파이썬에는 정말 다양한 함수들이 존재한..

Python 2017.10.27

[Python] 페이징 처리하기

이 내용을 어느 카테고리에 넣을지 고민하다가. 사용한 언어 카테고리에 넣는게 좋을 것 같아 여기다가 작성한다. python과 pymysql(MySQL)을 사용하여 페이징 처리를 해봤다. 일단, 간단히.pymysql을 사용하여 DB에 연결하는 방법def connect_db(): try: conn = pymysql.connect( host='', user='', password='', db='', charset='utf8', cursorclass=pymysql.cursors.DictCursor ) return conn except: print("DB connection Error") conn = connect_db() curs = conn.cursor() 페이징하는 첫번째 방법per_page = 100 # ..

Python 2017.10.24

[Python] Query String을 Dictionary로 바꾸기

쿼리스트링을 딕셔너리로 바꾸는 코드입니다. 코드from urllib.parse import urlsplit, parse_qsl data = dict(parse_qsl(urlsplit(query_string).path)) urllib.parse 쓰려면 저렇게 해줘야한대요. from urllib 해서 urllib.parse로 쓰면 오류 생깁니다잉 활용 예시query_string = 'email=abc@email.com&name=abc&id=1234' from urllib.parse import urlsplit, parse_qsl data = dict(parse_qsl(urlsplit(query_string).path)) >>> {'email': 'abc@email.com', 'name': 'abc', 'id..

Python 2017.10.12

[Python] Dictionary를 key/value 기준으로 정렬하기

sorted와 operator를 사용하면 간단하게 딕셔너리를 Key 또는 Value 기준으로 값들을 정렬할 수 있다. Dictionary의 key 기준으로 정렬하기import operatordata = sorted(dict_data.items(), key=operator.itemgetter(0)) Dictionary의 value 기준으로 정렬하기import operatordata = sorted(dict_data.items(), key=operator.itemgetter(1)) 설명1. 딕셔너리인 dict_data.items()를 통해 Key, Value 쌍을 튜플로 묶은 값을 얻는다. 2. sorted()의 인자값 'key'에 operator.itemgetter()로 기준을 설정해준다.itemgette..

Python 2017.10.12

[Python] subprocess, curl 활용하여 티켓 풀리면 알려주기

배타고 여행을 가려하는데 티켓이 언제풀릴지 몰라서 자리가 풀리면 이메일로 알려주는 코드를 짰다.만들생각 없었는데 같이 가는 사람들이 해달라그래서 했다. 결론은 못썼다.전화로 선박 회사에 물어보니 날짜와 시간을 알려주었 + 잘못짜서 이메일이 제대로 오지도 않았다. 그래도 이거 짜면서 새로 알게된 것이 있다. subprocess, curl 이다.subprocess는 Linux에 입력한 명령어의 결과를 파이썬으로 읽어들일 수 있도록 해준다.curl은 웹브라우저를 열어서 실행시켜준다. 내 코드import subprocess from subprocess import PIPE from bs4 import BeautifulSoup as BS import urllib.parse f = subprocess.Popen("..

Python 2017.10.12

[Python] 크롤링(Crawling) with ulrlib&BeautifulSoup

검색한 결과 가져오기 구글 검색 결과를 가져오는 코드 from bs4 import BeautifulSoup as BS import ssl, urllib import traceback base_url = 'https://www.google.co.kr/search' #: 검색조건 설정 values = { 'q': target, # 검색할 내용 'oq': target, 'aqs': 'chrome..69i57.35694j0j7', 'sourceid': 'chrome', 'ie': 'UTF-8', } # Google에서는 Header 설정 필요 hdr = {'User-Agent': 'Mozilla/5.0'} query_string = urllib.parse.urlencode(values) req = urllib...

Python 2017.08.08

[Python] PIL 사용해서 이미지 잘라내기/크롭

import io from PIL import Image # 받은 좌표를 crop()에 맞춰서 바꿔주기 # 나의 경우 (x, y, 자를 넓이, 자를 높이)로 요청이 들어와서 crop()에 맞춰서 바꿔줬어야 했다. # 입력받은 좌표를 이용하여 crop()한다. crop_img = img.crop(`좌표`) b = io.BytesIO() crop_img.save(b, format="PNG") img_bytes = b.getvalue() 좌표= (start_x, start_y, start_x + width, start_y + height) = (left, upper, right, lower) = (가로 시작점, 세로 시작점, 가로 범위, 세로 범위) 좌표는 왼쪽 윗 모서리를 (0,0)으로 잡는다. 튜플(tup..

Python 2017.08.07