2016년 4월 27일 수요일

연령대별 장래 인구 추계 (1960 ~ 2060)



통계청 자료로 만든 연령대별 장래 인구 추계. (1960 ~ 2060)
다들 얘기하는 노령화 사회로의 변화를 예고하고 있다.
말그대로 100세시대, '노후'에 대한 대비는 개인의 준비 문제가 아니라 사회의 문제로 심각하게 논의되어야 할 것 같다.

library(ggplot2)
library(dplyr)
library(scales)
library(reshape2)

df <- as.data.frame(read.csv("population2.csv", header=TRUE))
head(df)

df2 <- df %>% mutate(age_range2 = '0~14')
df2[4:13, ]$age_range2 <- '15~64'
df2[14:20, ]$age_range2 <- '65+'

df2m <- melt(cbind(df2[2:12], age_range=df2$age_range2), id.vars=c('age_range'))
levels(df2m$variable) <- gsub("X", "", levels(df2m$variable))

# for annotation
year_total <- 
  df2m %>% 
  group_by(Year) %>%
  summarise(year_total = sum(Percentage))

age_range_total <- df2m %>% 
  group_by(Year, age_range) %>% 
  summarise(avg = sum(Percentage))

df2m_tmp <- left_join(age_range_total, year_total, by="Year")
df2m_tmp <- df2m_tmp %>% mutate(prop = avg/year_total)
df2m_tmp <- df2m_tmp %>% mutate(cumsum = cumsum(prop))

# plotting with annotation
ggplot(df2m,aes(x = Year, y = Percentage, fill = age_range)) + 
  geom_bar(position = "fill",stat = "identity", ylab='percentage', xlab='year') + 
  scale_y_continuous(labels = percent_format()) +
  annotate(geom="text", 
           x=df2m_tmp$Year, 
           y=df2m_tmp$cumsum, 
           label=paste0(as.character(round(df2m_tmp$prop*100, digits=1)),'%'), size=4) 


2016년 4월 5일 화요일

Python request package exception handling

사이트 목록을 돌며 title 내용을 가져오는 간단한 크롤링 코드를 짜서 돌리다가,
목록 중간 특정 웹사이트에서  에러가 발생하여 exception catch 처리한 내용. 기록/메모를 위해 남겨둔다.

[error msg] 
requests.exceptions.ConnectionError: HTTPConnectionPool(host='hostname', port=80): Max retries exceeded with url: hostname ...

response == none 인 경우를 잡아내 주면 보통 문제없이 돌았었는데, 이번처럼 request pkg의 ConnectionError를 handling 안해주면 죽는 경우가 생긴다. 

[Code]
import requests as rq
import bs4

header = {'User-Agent':'Mozilla/5.0'}

def get_html_title(url):        
    request = rq.Request('Get', url, headers = header)
    r = request.prepare()
    s = rq.Session()
    try: 
        response = s.send(r)
    except rq.exceptions.ConnectionError:
        return ''
    if response == None: 
        return ''
    html_content = response.text    
    navigator = bs4.BeautifulSoup(html_content, "html.parser")    
    title = navigator.find('title')
    if title == None:
        return ''
    return title.get_text() 

[Request PKG의 Exception Case]
http://docs.python-requests.org/en/latest/user/quickstart/#errors-and-exceptions

Errors and Exceptions

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise aConnectionError exception.
In the rare event of an invalid HTTP response, Requests will raise an HTTPError exception.
If a request times out, a Timeout exception is raised.
If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.
All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.