본문 바로가기
반응형

python72

[Python] get number from string #텍스트에서 숫자만 가져오기 Python '25일 전', '1249 views' 등 에서 숫자인 25, 1249 만 뽑아낼 때, 간단하게 이렇게 씁니다. str1 = "25 일 전" days = int(''.join(list(filter(str.isdigit, str1)))) print(days) # 25 이 코드의 문제점 str1 = "-50 포인트" points = int(''.join(list(filter(str.isdigit, str1)))) print(points) # 50 마이너스 처리가 안됩니다 ;; 마이너스는 re 로 해결 위의 문제점은 아래와 같이 re 를 사용해서 해결할 수 있습니다. import re str1 = "-50 포인트" result = [int(d) for d in re.findall(r'-?\d+',.. 2020. 9. 6.
[Python] list 를 text file 에 한줄씩 쓰기 ( \n 안나오게 ) Python List 의 각 요소를 text file 에 한줄씩 쓰기 testList = ['123', '456', 'abc', 'def'] 123 456 abc def filePath = './test.txt' testList = ['123', '456', 'abc', 'def'] with open(filePath, 'w+') as lf: lf.write('\n'.join(testList)) # 이렇게 하면 안됩니다~ 그런데 문제는 저 텍스트 파일을 읽어 들이면? filePath = './test.txt' testList = ['123', '456', 'abc', 'def'] with open(filePath, 'w+') as lf: lf.write('\n'.join(testList)) with ope.. 2020. 9. 5.
[Python] scheduler 사용하기 #APScheduler Python apscheduler 매달, 매달 특정일, 매일, 매일 특정 시간,분,초 등등 원하는 시간에 python script 를 실행하고 싶을 때 사용합니다. 대표적인것으로 schedule 와 apscheduler 가 있는데 apscheduler 사용법을 알아보겠습니다. pip install APScheduler 자주 사용하는 BlockingScheduler 와 BackgroundScheduler 를 설명하겠습니다. 소스로 이해하기 - BlockingScheduler import time from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() # 매일 12시 30분에 실행 @sched.sched.. 2020. 9. 4.
Python Decorator 파라메터 사용하기 #decorator parameter Python Decorator Parameter Python Decorator 의 개념은 이전 글에서 보시고 2020/09/03 - [Python] - Python Decorator 란? 사용 방법. #Python Decorator 바로 소스 코드 보시죠. 이번 샘플 소스는 각 메소드에서 오류 발생 시 처리를 Decorator 에서 하도록 하기위함입니다. 우선 데코레이터 없는 소스 class some_class(): def __init__(self): self.resJson = {} def setResponse(self, resJson): self.resJson = resJson def isSuccess(self): try: return self.resJson['code']==0 except Except.. 2020. 9. 3.
[Python] UUID, GUID 생성하기 아래와 같이 사용하면 됩니다. import uuid url = 'https://my.home.com/ print(uuid.uuid1()) print(uuid.uuid3(uuid.NAMESPACE_URL, url)) print(uuid.uuid4()) print(uuid.uuid5(uuid.NAMESPACE_URL, url)) 결과는 uuid1 은 호스트ID, 현재시간을 기준으로 uuid 생성 uuid3 네임스페이스의 uuid 와 이름의 MD5를 생성. uuid4 랜덤 uuid 생성 uuid5 네임스페이스uuid 와 이름의 SHA-1 해시에서 UUID 생성. 2020. 7. 5.
[Python] 특수문자 제거, HTML 태그 제거 특수문자 제거 import re test = 'hello! bryan~@@ 안녕~' pattern = '[^\w\s]' print(re.sub(pattern=pattern, repl='', string=test)) 결과는 hello bryan 안녕 HTML 태그 제거 import re test = 'hello! bryan~@@ 안녕~' pattern = ']*>' print(re.sub(pattern=pattern, repl='', string=test)) 결과는 hello! bryan~@@ 안녕~ 2020. 6. 25.
[Python] Selenium 웹페이지 스크롤하기 scrollTo, Scroll down Python 의 selenium 을 이용해서 스크롤 하기 크롤링 할 때 웹페이지를 스크롤 다운해야하는 경우가 있죠. 스크롤다운해서 끝까지 가야 그 다음 데이터를 조회하는 경우가 있고 그 외에도 필요한 경우가 있습니다. 방법 1. scrollTo driver.execute_script("window.scrollTo(0, Y)") 여기서 Y 는 height 을 입력하면 됩니다. 페이지 끝까지 가려면 document.body.scrollHeight 를 사용합니다. 계속해서 스크롤 다운하면서 데이터를 다 조회할때는 SCROLL_PAUSE_SEC = 1 # 스크롤 높이 가져옴 last_height = driver.execute_script("return document.body.scrollHeight") whil.. 2020. 6. 18.
[ChromeDriver] 크롬 드라이버 버전에 따라 설정하는 방법 우선 크롬 버전을 확인합니다. Chrome 정보 클릭. 83. 어쩌고 버전입니다. 크롬드라이버 다운로드 사이트로 갑니다. https://chromedriver.chromium.org/downloads 여기서 버전에 맞는 링크를 클릭합니다. 아래와 같은 페이지가 열립니다. 전 윈도우에서 할거니까 win 버전으로. (64는없네요) 다운받으면 .zip 파일입니다. 압축을 풀고 chromedriver.exe 경로를 파이선 코드에서 사용하면 됩니다. python 예시 chrome_driver_path = "D:/dev/crawling/chromedriver.exe" driver = webdriver.Chrome(chrome_driver_path, chrome_options=options, desired_capab.. 2020. 6. 9.
[Python] gif 이미지 opencv 로 로드하기 cv2 python opencvcv2 imread gif gif 를 cv2.imread('./test.gif')이렇게 읽으면 오류가 납니다.gif 는 여러개의 이미지가 존재하는 video 같은거라고 보면 됩니다.frame 을 읽어와야죠. 이미지가 gif 형식이면 첫번째 frame 만 읽어오는 함수입니다.import cv2import numpy as np def loadImageFromPath(imgPath): try: # gif 처리 if str(imgPath).lower().endswith('.gif'): gif = cv2.VideoCapture(imgPath) ret, frame = gif.read.. 2020. 5. 18.
[python] 실행 명령어에 파라메터 추가하기 python 파라메터 추가 test.py if __name__ == '__main__' : print('hello~') 이런 코드가 있을 때 실행 명령은 $ python test.py 이렇게 실행하죠. 아래와 같이 실행명령어 뒤에 파라메터를 추가하려면 $ python test.py --name bryan -a 100 argparse 를 import 합니다. import argparse 그리고 사용 소스는 import argparse if __name__ == '__main__' : parser = argparse.ArgumentParser() parser.add_argument("--name", "-n", help="user name", default='jjang-gu') parser.add_argume.. 2020. 2. 17.
728x90
반응형