지난 수업 이후로 Python 에서 기본 모듈로 구현가능한 내용들 정리하기
목적 : 생성한 Dict 객체 호출시 기본값을 특정하여 오류처리 없이도 전체 과정이 진행
import math
math.ceil(3.14) # 올림 : 결과는 4
4
math.floor(3.14) # 내림 : 결과는 3
3
math.trunc(-3.14) # trunc() 내림을 해도 0을 향한다
-3
round(3.1415) # 반올림 : Python 내장함수를 사용
3
from collections import defaultdict
int_dict = defaultdict(int)
int_dict
defaultdict(int, {})
# 입력값이 없어도, 호출시 "int" 를 자동생성
# 작업 과정에 오류가 있어도 Dict 객체를 생성
print(int_dict['key1'])
int_dict
0
defaultdict(int, {'key1': 0})
int_dict['key2'] = 'test'
int_dict
defaultdict(int, {'key1': 0, 'key2': 'test'})
int_dict['key3']
int_dict
defaultdict(int, {'key1': 0, 'key2': 'test', 'key3': 0})
dict 객체를 순서에 따라 정렬할 필요가 있을때
col_to_kor = {
"NUM":"번호",
"FOOD_CD":"식품코드",
"DESC_KOR":"식품이름",
"SERVING_WT":"1회제공량(g)",
}
from collections import OrderedDict
json_keys = OrderedDict(col_to_kor)
json_keys
OrderedDict([('NUM', '번호'), ('FOOD_CD', '식품코드'), ('DESC_KOR', '식품이름'), ('SERVING_WT', '1회제공량(g)')])
list(OrderedDict(col_to_kor).keys())
['NUM', 'FOOD_CD', 'DESC_KOR', 'SERVING_WT']
python 의 기본 datetime 객체 다루기
Python 에서 기본 Datetime 객체 다루기
from datetime import datetime, timedelta
print(datetime.today().strftime("%A %d. %B %Y"))
print(datetime.today().strftime('%Y-%m-%d'))
# 년, 월, 일, 시간, 분, 초
datetime(2019,10,10,12,12,12,1000)
Monday 21. October 2019 2019-10-21
datetime.datetime(2019, 10, 10, 12, 12, 12, 1000)
# 수치를 활용한 보간
# 날짜를 연산으로 변환된 값을 추출 가능
datetime(2019,10,10) - timedelta(10)
datetime.datetime(2019, 9, 30, 0, 0)
datetime.strptime('20190101', '%Y%d%m')
datetime.datetime(2019, 1, 1, 0, 0)
datetime 객체를 활용하는 Pandas 모듈
# 10일의 기간 출력
import pandas as pd
pd.date_range('2019/01/01', periods=10)
DatetimeIndex(['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04', '2019-01-05', '2019-01-06', '2019-01-07', '2019-01-08', '2019-01-09', '2019-01-10'], dtype='datetime64[ns]', freq='D')
# 10일의 기간 출력
pd.date_range('2019/01/01', periods=10, freq='B')
DatetimeIndex(['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04', '2019-01-07', '2019-01-08', '2019-01-09', '2019-01-10', '2019-01-11', '2019-01-14'], dtype='datetime64[ns]', freq='B')
# 10일의 기간 출력
pd.date_range('2019/01/01', periods=10, freq='12h30min', normalize=True)
DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 12:30:00', '2019-01-02 01:00:00', '2019-01-02 13:30:00', '2019-01-03 02:00:00', '2019-01-03 14:30:00', '2019-01-04 03:00:00', '2019-01-04 15:30:00', '2019-01-05 04:00:00', '2019-01-05 16:30:00'], dtype='datetime64[ns]', freq='750T')
# 기간 구간을 10개로 나누기
pd.date_range('2019/01/01', '2019/11/01', periods=10)
DatetimeIndex(['2019-01-01 00:00:00', '2019-02-03 18:40:00', '2019-03-09 13:20:00', '2019-04-12 08:00:00', '2019-05-16 02:40:00', '2019-06-18 21:20:00', '2019-07-22 16:00:00', '2019-08-25 10:40:00', '2019-09-28 05:20:00', '2019-11-01 00:00:00'], dtype='datetime64[ns]', freq=None)
# String Format time data
# 개별 객체에 datetime 메소드를 적용
[_.strftime('%Y-%m-%d') for _ in pd.date_range('2019/10/10', periods=5)]
['2019-10-10', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14']
! pip install -U instabot
Requirement already up-to-date: instabot in /home/momukji/Python/Python/lib/python3.6/site-packages (0.89.0) Requirement already satisfied, skipping upgrade: schedule>=0.6.0 in /home/momukji/Python/Python/lib/python3.6/site-packages (from instabot) (0.6.0) Requirement already satisfied, skipping upgrade: huepy>=0.9.8.1 in /home/momukji/Python/Python/lib/python3.6/site-packages (from instabot) (1.2.1) Requirement already satisfied, skipping upgrade: pysocks>=1.6.8 in /home/momukji/Python/Python/lib/python3.6/site-packages (from instabot) (1.7.1) Requirement already satisfied, skipping upgrade: responses>=0.10.5 in /home/momukji/Python/Python/lib/python3.6/site-packages (from instabot) (0.10.9) Requirement already satisfied, skipping upgrade: future>=0.17.1 in /home/momukji/Python/Python/lib/python3.6/site-packages (from instabot) (0.18.2) Requirement already satisfied, skipping upgrade: pytz>=2019.1 in /home/momukji/Python/Python/lib/python3.6/site-packages (from instabot) (2019.3) Requirement already satisfied, skipping upgrade: requests>=2.21.0 in /home/momukji/Python/Python/lib/python3.6/site-packages (from instabot) (2.21.0) Requirement already satisfied, skipping upgrade: tqdm>=4.30.0 in /home/momukji/Python/Python/lib/python3.6/site-packages (from instabot) (4.36.1) Requirement already satisfied, skipping upgrade: requests-toolbelt>=0.8.0 in /home/momukji/Python/Python/lib/python3.6/site-packages (from instabot) (0.9.1) Requirement already satisfied, skipping upgrade: six>=1.12.0 in /home/momukji/Python/Python/lib/python3.6/site-packages (from instabot) (1.12.0) Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /home/momukji/Python/Python/lib/python3.6/site-packages (from requests>=2.21.0->instabot) (2.8) Requirement already satisfied, skipping upgrade: urllib3<1.25,>=1.21.1 in /home/momukji/Python/Python/lib/python3.6/site-packages (from requests>=2.21.0->instabot) (1.24.3) Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /home/momukji/Python/Python/lib/python3.6/site-packages (from requests>=2.21.0->instabot) (2019.9.11) Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /home/momukji/Python/Python/lib/python3.6/site-packages (from requests>=2.21.0->instabot) (3.0.4)
from instabot import Bot
bot = Bot()
bot.login(username="saltman21@naver.com", password="inst8472")
# bot.login(username="YOUR_LOGIN", password="YOUR_PASSWORD")
user_id = bot.get_user_id_from_username("erdoskim")
user_info = bot.get_user_info(user_id)
print(user_info['biography'])
2020-01-02 17:13:32,482 - INFO - Instabot Started
from igramscraper.instagram import Instagram
instagram = Instagram()
# authentication supported
instagram.with_credentials('erdoskim', 'inst8472')
instagram.login()
#Getting an account by id
account = instagram.get_account_by_id(3)
--------------------------------------------------------------------------- InstagramException Traceback (most recent call last) <ipython-input-64-386d66eaf47f> in <module> 8 9 #Getting an account by id ---> 10 account = instagram.get_account_by_id(3) ~/Python/Python/lib/python3.6/site-packages/igramscraper/instagram.py in get_account_by_id(self, id) 108 :return: Account 109 """ --> 110 username = self.get_username_by_id(id) 111 return self.get_account(username) 112 ~/Python/Python/lib/python3.6/site-packages/igramscraper/instagram.py in get_username_by_id(self, id) 127 if Instagram.HTTP_OK != response.status_code: 128 raise InstagramException.default(response.text, --> 129 response.status_code) 130 131 json_response = response.json() InstagramException: Response code is 400. Body: {"message": "useragent mismatch", "status": "fail"} Something went wrong. Please report issue., Code:400
# Available fields
print('Account info:')
print('Id: ', account.identifier)
print('Username: ', account.username)
print('Full name: ', account.full_name)
print('Biography: ', account.biography)
print('Profile pic url: ', account.get_profile_pic_url_hd())
print('External Url: ', account.external_url)
print('Number of published posts: ', account.media_count)
print('Number of followers: ', account.followed_by_count)
print('Number of follows: ', account.follows_count)
print('Is private: ', account.is_private)
print('Is verified: ', account.is_verified)
# or simply for printing use
print(account)
--------------------------------------------------------------------------- InstagramException Traceback (most recent call last) <ipython-input-61-c38177b46960> in <module> 8 9 #Getting an account by id ---> 10 account = instagram.get_account_by_id(3) 11 12 # Available fields ~/Python/Python/lib/python3.6/site-packages/igramscraper/instagram.py in get_account_by_id(self, id) 108 :return: Account 109 """ --> 110 username = self.get_username_by_id(id) 111 return self.get_account(username) 112 ~/Python/Python/lib/python3.6/site-packages/igramscraper/instagram.py in get_username_by_id(self, id) 127 if Instagram.HTTP_OK != response.status_code: 128 raise InstagramException.default(response.text, --> 129 response.status_code) 130 131 json_response = response.json() InstagramException: Response code is 400. Body: {"message": "useragent mismatch", "status": "fail"} Something went wrong. Please report issue., Code:400
a = [1,2,3]
b = [1,2,3]
a is b
False
a == b
True
%reset
def uppercase(func):
def wrapper():
return func().upper()
return wrapper
@uppercase
def greet():
return 'hello boys!!'
greet('hello boys!')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-55-51c96caae186> in <module> ----> 1 greet('hello boys!') TypeError: wrapper() takes 0 positional arguments but 1 was given
def decor1(func):
def wrap():
print("$$$$$$$$$$$$$$")
func()
print("$$$$$$$$$$$$$$")
return func.upper()
return wrap
@decor1
def sayhello():
print("Hello")
sayhello()
$$$$$$$$$$$$$$ Hello $$$$$$$$$$$$$$
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-51-d038986f5dac> in <module> 2 def sayhello(): 3 print("Hello") ----> 4 sayhello() <ipython-input-50-075fc5d856e2> in wrap() 4 func() 5 print("$$$$$$$$$$$$$$") ----> 6 return func.upper() 7 return wrap AttributeError: 'function' object has no attribute 'upper'
>>> def decor2(func):
def wrap():
print("##############")
func()
print("##############")
return wrap