해시코드 질문 키워드
- bs4와 wordcloud를 이용해서 질문 키워드를 보여주는 시각화를 진행합니다.
질문 텍스트 스크래핑
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)