생활
파이썬 문제 도움 부탁드립니다.
네이버 뉴스에서 주어진 키워드에 해당하는 뉴스 기사의 타이틀을 실시간으로 크롤링하여 워드 클라우드로 시각화 하세요. (l 크롤링 키워드 : 신종 코로나)
>>빈칸에 있는것만 채우면 되는데 3,4,5번에서 막혔습니다... 부탁드립니다. !!
from bs4 import BeautifulSoup
import requests
from konlpy.tag import Okt
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import pandas as pd
# 키워드 검색 뉴스 가사 타이틀 가져오기
def getnewstitles(startnum, endnum):
while True :
if startnum > endnum:
break
url = 'https://search.naver.com/search.naver?where=news&sm=tab_jum&query={}&start={}'.format(searchword, startnum)
response = requests.get(url)
html = response.text
1. soup = BeautifulSoup(source, 'html.parser')
# 뉴스 타이틀 가져오기
2. titles = soup.select ('ul.type01 > li > dl > dt > a')
# 뉴스 타이틀을 list에 저장
for title in titles:
title_list.append(title['title'])
start_num += 10 # 읽어올 기사 수 조정
# 수집한 기사 타이틀 출력
for no, title in enumerate(title_list, start=1) :
print(no, title)
print("-"* 120)
# 워드 클라우드 그리기
def make_wordcloud(wordcount):
okt = Okt()
sentences_tag = []
# 형태소로 분석하여 리스트에 넣기
for sentence in title_list:
morph = okt.pos(sentence)
sentences_tag.append(morph)
nounadjlist = []
# 형태소 중 명사와 형용사만 리스트에 넣기
for sentence in sentences_tag:
for word, tag in sentence:
if tag in ['Noun', 'Adjective']:
nounadjlist.append(word)
# 단어 빈도수 세기
count = Counter(nounadjlist)
# 빈도수가 높은 단어 50개 추출, 글자 길이가 2이상인 단어만 추출
wordInfo = dict()
for tags, counts in count.most_common(wordcount):
if len(wordInfo) >= 50 : # 빈도수가 높은 단어 50개 추출
break
if (len(str(tags)) > 1): # 글자 길이가 2이상인 단어만 추출
wordInfo[tags] = counts
print ("%s : %d" % (tags, counts))
# wordcloud 객체 생성(한글깨지는 문제 해결하기위해 font_path 지정)
font_path = '/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf'
wc = WordCloud(fontpath = fontpath,
background_color='white', width=600, height=480)
# wordcloud 객체에 데이터 매핑
wc.generatefromfrequencies(wordInfo)
# wordcloud 그리기
plt.figure(figsize=(10, 6))
plt.axis('off')
plt.imshow(wc)
plt.show()
# 메인 프로그램
if name == 'main':
3. search_word = # 키워드 검색
title_list = []
# 뉴스 기사 타이틀 크롤링(시작 ~ 끝)
4. (1, 50)
# 워드클라우드 그리기
5. (100)
1개의 답변이 있어요!