시각화로 결과 요약하기 - Seaborn : 4-5. 워드클라우드 만들기

임동윤·2022년 9월 30일
0

웹 스크래핑 기초

목록 보기
20/20
post-thumbnail

해시코드 질문 키워드

  • bs4와 wordcloud를 이용해서 질문 키워드를 보여주는 시각화를 진행합니다.

질문 텍스트 스크래핑

  • 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"}
  • Pagination이 되어있는 질문 리스트의 제목을 모두 가져와 리스트 questions에 저장 합니다.
import time
import requests
from bs4 import BeautifulSoup

questions = []

for i in range(1,5):
    res = requests.get("https://hashcode.co.kr/?page={}".format(i), user_agent)
    soup = BeautifulSoup(res.text, "html.parser")
  
    parsed_datas = soup.find_all("li", "question-list-item")
    for data in parsed_datas:
        questions.append(data.h4.text.strip())
   
    time.sleep(0.5)
   
questions[:10]

WordCloud 만들기

  • WordCloud를 그리기 위해 필요한 라이브러리를 불러옵니다.
# 문장에서 명사를 추출하는 형태소 분석 라이브러리
from konlpy.tag import Hannanum

# 횟수를 기반으로 딕셔너리 생성
from collections import Counter

# 시각화에 쓰이는 라이브러리
import matplotlib.pyplot as plt
from wordcloud import WordCloud

KoNLPy 라이브러리로 한국어 문장을 전처리

  • Hannanum객체를 생성한 후, .nouns()를 통해 명사를 추출합니다.
words = []

hannanum = Hannanum()
for question in questions:
    nouns = hannanum.nouns(question)
    words += nouns
   
print(len(words))

Counter 를 이용해 빈도수 측정

  • counter를 이용해 각 단어의 개수를 세줍니다.
counter = Counter(words)
print(counter)

WordCloud를 이용해 시각화

  • 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)


profile
AI Tensorflow Python

0개의 댓글