본문 바로가기

데이터엔지니어링

[2주차] 파이썬으로 웹다루기 (5)

🙂 시각화 라이브러리, Seaborn

데이터 스크래핑의 결과는 텍스트 형태.

한 눈에 요약해서 보여주는 방법: 시각화

 

✔  seaborn

matplotlib을 기반으로 하는 시각화 라이브러리

다양한 그래프를 고수준(high-level)에서 쉽게 그릴 수 있음.

%pip install seaborn

 

import seaborn as sns

## 꺾은선 그래프 (Line Plot)
sns.lineplot(x=[1, 3, 2, 4], y=[0.7, 0.2, 0.1, 0.05])

## 막대 그래프 (Bar Plot)
sns.barplot(x=['Amy', 'Bob', 'Cat', 'Dog'], y=[0.7, 0.2, 0.1, 0.05])

 

✔  Plot

import matplotlib.pyplot as plt

plt.figure(figsize = (20, 10))	# plt의 크기 지정

sns.lineplot(x=[1,2,3,4], y=[0.7, 0.2, 0.1, 0.05])

plt.title('Bar Plot')	# plt의 이름 결정

plt.xlabel('X Label')	# x축 이름
plt.ylabel('Y Label')	# y축 이름

plt.ylim(0, 10)		# y축 범위 결정

plt.show()

🙂 시각화

✔  기상청 날씨 정보 시각화하기

참조 사이트: https://www.weather.go.kr/w/weather/forecast/short-term.do

  1. 스크래핑에 필요한 라이브러리 불러오기
    from selenium import webdriver
    from webdriver_manager.chrome import ChromeDriverManager
    from selenium.sebdriver.chrome.service import Service
    from selenium.sebdriver.common.by import By​
  2. driver를 이용해 해당 사이트에 요청 보내기
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
    
    driver.get('https://www.weather.go.kr/w/weather/forecast/short-term.do')
    driver.implicitly_wait(1)
    
    temps = driver.find_element(By.ID, 'my-tchart').text
    
    temps = [int(i) for i in temps.replace('℃', '').split('\n')]
  3. 꺾은선 그래프(Line Plot)을 이용해 앞으로의 기온 추이를 나타내기
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    plt.ylim(min(temps)-2, max(temps)+2)
    plt.title('Expected Temperature from now on')
    
    sns.lineplot(x=[i for i in range(len(temps))], y=temps)
    
    plt.show()​

✔  해시코드 질문코드 빈도

참조 사이트: https://hashcode.co.kr/

  1. User-Agent 추가
    user_agent = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}​
  2. 필요한 라이브러리 호출
    import requests
    from bs4 import BeautifulSoup
    
    import time
    
    frequency = {}
    
    for i in range(1, 11):
        res = requests.get('https://hashcode.co.kr/?page={}'.format(i), user_agent)
        soup = BeautifulSoup(res.text, 'html.parser')
    
        ## 1. ul 태그를 모두 찾기
        ## 2. 1번 안에 있는 li 태그의 text를 추출
        ul_tags = soup.find_all('ul', 'question-tags')
        for ul in ul_tags:
            li_tags = ul.find_all('li')
            for li in li_tags:
            	tag = li.text.strip()
                if tag not in frequency:
                	frequency[tag] = 1
                else:
                	frequency[tag] += 1
        
        time.sleep(0.5)
    
    print(frequency)​
  3. Counter를 사용해 가장 빈도가 높은 Value 추출
    from collections import Counter
    
    counter = Counter(frequency)
    counter.most_common(10)	# 상위 10개 추출​
  4. Seaborn을 이용해 Barplot화
    import seaborn as sns
    
    x = [elem[0] for elem in counter.most_common(10)]
    y = [elem[1] for elem in counter.most_common(10)]
    
    sns.barplot(x=x, y=y)​
  5. figure, xlabel, ylabel, title 설정해서 시각화
    import matplotlib.pyplot as plt
    
    plt.figure(figsize=(20, 10))
    plt.title('Frequency of question in Hashcode')
    plt.xlabel('Tag')
    plt.ylabel('Frequency')
    
    sns.barplot(x=x, y=y)
    
    plt.show()​

🙂 Wordcloud

✔  Wordcloud

자주 등장하는 텍스트를 중요도나 인기도를 고려해 표현한 것

  1. 자연어 문장에서 키워드를 추출
    '파이썬에서 반복문을 어떻게 사용하나요?' -> ['파이썬', '반복문', '사용']
  2. 키워드가 등장한 빈도를 측정
    ['파이썬', '반복문', '사용'] -> {'파이썬': 1, '반복문': 1, '사용': 1}
  3. 앞에서 전처리한 정보와 Wordcloud 라이브러리를 바탕으로 Wordcloud 생성
    {'파이썬': 1, '반복문': 1, '사용': 1} -> Wordcloud

✔  Wordcloud 만들어보기

wordcloud는 파이썬이 텍스트 클라우드 라이브러리

konlpy는 한국어 형태소 분석기 라이브러리. 주어진 문장에서 명사 등을 뽑는 데 사용.

%pip install wordcloud
%pip install konlpy
  1. KoNLPy 라이브러리로 한국어 문장을 전처리
    # 시각화에 쓰이는 라이브러리
    import matplotlib.pyplot as plt
    from wordcloud import WordCloud
    
    # 횟수를 기반으로 딕셔너리 생성
    from collections import Counter
    
    # 문장에서 명사를 추출하는 형태소 분석 라이브러리
    from konlpy.tag import Hannanum
    
    # 워드클라우드를 만드는 데 사용할 애국가 가사
    national_anthem = """
    동해물과 백두산이 마르고 닳도록
    하느님이 보우하사 우리나라 만세
    무궁화 삼천리 화려 강산
    대한 사람, 대한으로 길이 보전하세
    남산 위에 저 소나무, 철갑을 두른 듯
    바람 서리 불변함은 우리 기상일세
    무궁화 삼천리 화려 강산
    대한 사람, 대한으로 길이 보전하세
    가을 하늘 공활한데 높고 구름 없이
    밝은 달은 우리 가슴 일편단심일세
    무궁화 삼천리 화려 강산
    대한 사람, 대한으로 길이 보전하세
    이 기상과 이 맘으로 충성을 다하여
    괴로우나 즐거우나 나라 사랑하세
    무궁화 삼천리 화려 강산
    대한 사람, 대한으로 길이 보전하세
    """
    ## hannanum 객체를 생성 후, .nouns()를 통해 명사를 추출
    ## JAVA 미설치 시 에러 발생할 수 있음.
    
    hannanum = Hannanum()
    nouns = hannanum.nouns(national_anthem)
    
    nouns[:10]
  2. Counter를 이용해 빈도수 측정
    counter = Counter(nouns)​
  3. WordCloud를 이용해 시각화
    wordcloud = WordCloud(
    	font_path="C:\Windows\Fonts\H2GPRM.TTF",
        background_color = 'white',
        width = 1000,
        height = 1000,
    )
    
    img = wordcloud.generate_from_frequencies(counter)
    plt.imshow(img)

    한국어의 경우 폰트 설정 필요.

✔  해시코드 질문 키워드

  1. hashcode 사이트에서 질문을 가져온다.
    import requests
    from bs4 import BeautifulSoup
    import time
    
    questions = []
    user_agent = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}
    
    for i in range(1, 6):
        res = requests.get('https://hashcode.co.kr/?page={}'.format(i), user_agent)
        soup = BeautifulSoup(res.text, 'html.parser')
    
    	parsed_data = soup.find_all('li', 'question-list-item')
        
        for data in parsed_data:
        	questions.append(data.h4.text.strip())
            
        time.sleep(0.5)
  2. 텍스트 구름을 그리기 위해 필요한 라이브러리 호출
    import matplotlib.pyplot as plt
    from wordcloud import WordCloud
    from collections import Counter
    from konlpy.tag import Hannanum​
  3. Hannanum 객체를 생성한 후, .nouns()를 통해 명사 추출
    hannanum = Hannannum()
    
    words = []
    
    for question in questions:
    	nouns = hannanum.nouns(question)
        words += nouns​
  4. Counter를 이용해 각 단어의 개수 책정
    counter = Counter(words)​
  5. WordCloud를 이용해 텍스트 구름 생성
    wordcloud = WordCloud(
    	font_path="C:\Windows\Fonts\H2GPRM.TTF",
        background_color = 'white',
        height=1000,
        width=1000,
    )
    
    img = wordcloud.generate_from_frequencies(counter)
    plt.imshow()​