파이썬 크롤링 연습(3) 랭킹 기사로 워드클라우드 만들기

2020. 7. 22. 08:30캐리의 데이터 세상/파이썬

반응형

7월 21일 자 네이버 랭킹 기사 크롤링한 데이터를 가지고 와서 Pandas로 DataFrame을 만들고 자연어 처리 후 워드 클라우드로 간단하게 만들어 보겠습니다. 이번에는 soynlp로만 처리하고 KoNLPy 오픈소스 활용 예시는 다음 포스팅에서 정리해 보겠습니다.

참고로 저는 이제 막 배우기 시작한 초보자인 점을 감안하여 자세한 함수 정의와 예시는 링크의 정식 라이브러리 혹은 API를 참조해 주세요. 그날그날 배운 거 정리하면서 다시 한번 코드 작성해 보는 공간입니다:)

▶ 지난 포스팅 참조

2020/07/21 - [캐리의 데이터 세상/캐리의 데이터 공부 기록] - 파이썬 크롤링 연습(2) - 랭킹 뉴스 끌어오기

지난 크롤링 포스팅에 pandas를 불러오고 output 문구 정리를 좀더 한 후에 하기와 같이 데이터를 "navernews.csv"라는 파일로 생성했습니다.

 

from bs4 import BeautifulSoup
import requests,time
import pandas as pd

news=[]
url="https://news.naver.com/main/ranking/popularDay.nhn"
r=requests.get(url)

soup = BeautifulSoup(r.text,'html.parser')
results=soup.select('.section_list_ranking li a')
#class명 'section_list_ranking' 하위의 <li> 태그 하위 <a>태그 문자열 select!

for result in results:
#     print('기사 제목:',result.attrs['title'])
#     print('기사 링크:',result.attrs['href'])
#     print() # 기사 전문과 링크 사이 공백여유주기
#     print()
    title=result.attrs['title']
    href=result.attrs['href']
    url_content='https://news.naver.com'+result.attrs['href']
    response_content = requests.get(url_content)
    soup_content=BeautifulSoup(response_content.text,'html.parser')
    content=soup_content.select_one('#articleBodyContents')
    # print(content.contents) #print해보면 가공전의 각종 태그,주석,공백들 혼합되어있음
    
    # 데이터 가공하기
    output=''
    for item in content.contents:
        stripped=str(item).strip() # strip()으로 공백제거
        if stripped=='':
            continue
        if stripped[0] not in['<','/']: #태그나 주석제거
            output+=str(item).strip()
    output=output.replace('본문 내용TV플레이어','')
    output=output.replace('// flash 오류를 우회하기 위한 함수 추가','')
    output=output.replace('function _flash_removeCallback() {}','')
    output=output.strip()
    news.append({'title':title,'href':href,'contents':output})
    
print(news)
time.sleep(2)
    
# #print(news)    
dataframe=pd.DataFrame(news)
dataframe=dataframe.set_index('title')
dataframe.to_csv("navernews.csv")

 

가공 전에 print로 한번 출력해 보면 기사 전문 중간중간에 링크와 특수문자, 'function _flash_removeCallback() {}' 등등 필요 없는 내용들이 기사마다 포함되어 있는데요, replace 함수를 써서 처리 후 news 리스트에 append로 하나씩 담았습니다. 

dataframe에서는 set_index 함수를 써서 'title'을 인덱스 열로 바꿔주고 기존의 자동으로 부여되는 인덱스 숫자열을 없애버렸습니다.

파이썬 데이터 추출 가공 처리 전
문자열 가공 처리 전

6개 섹션의 10개씩 기사니 csv파일로 데이터가 정확히 60행까지 잘 들어갔습니다. 

pandas로 데이터 프레임 생성
데이터 프레임 

이제 만들어 놓은 csv파일을 불러내어 자연어 처리를 한 후 워드클라우드로 만들어 보겠습니다.

먼저 임의로 stopwords_kr 리스트에 불필요한 단어들(맺음말, 접속사, 지시어 등등)을 넣고 출력해 본 다음, sonlpy로 처리한 것과 비교해 보겠습니다.

import pandas as pd
df = pd.read_csv('navernews.csv', engine='python', encoding='utf-8')

stopwords_kr =['있다','있습니다','있는','하는','것이다','밝혔다','위해','대해','했다','재배포','21일','따르면','무단전재','관계자는','기자','것으로','말했다']

from wordcloud import WordCloud
import matplotlib.pyplot as plt
%matplotlib inline

def displayWordCloud(data = None, backgroundcolor = 'black', width=800, height=600 ):
    wordcloud = WordCloud(
                        font_path = 'C:\\Users\\admin\\AppData\\Local\\Microsoft\\Windows\\Fonts\\NanumGothicEcoR.ttf',
                        stopwords= stopwords_kr,
                        background_color = backgroundcolor,
                        width = width, height = height).generate(data)
    print(wordcloud.words_)
    plt.figure(figsize = (15, 10))
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()

 

#데이터 프레임 구성이 어떻게 되어 있는지 확인! (60,3)으로 출력되는데요, 60개의 행과 3개의 열(title, href, contents)로 구성!

df.shape

워드 클라우드 출력 호출합니다. (※ WordCloud를 시작하기 전에 prompt 창으로 install 먼저 하기)

displayWordCloud(''.join(df['contents']))

파이썬 워드클라우드 만들기
워드클라우드 - 네이버 랭킹기사

 

이번엔 sonlpy로 처리 후 출력해 보겠습니다.

■ sonlpy는 한국어 분석을 위한 pure python code입니다. 학습 데이터를 이용하지 않으면서 데이터에 존재하는 단어를 찾거나, 문장을 단어 열로 분해, 혹은 품사 판별을 할 수 있는 비지도 학습 접근법을 지향(출처 : 깃헙 - github.com/lovit/soynlp )

import pandas as pd
df = pd.read_csv('navernews.csv', engine='python', encoding='utf-8')

from soynlp.noun import NewsNounExtractor
noun_extractor = NewsNounExtractor()
nouns = noun_extractor.train_extract(df['contents'])

displayWordCloud(' '.join(nouns))

3가지 버전 중에 News Noun Extractor 를 이용했습니다.

soynlp처리 파이썬 워드클라우드
soynlp - News Noun Extractor 사용 워드클라우드

60개의 전체 기사중에서 특정 단어가 포함된 기사들을 찾아서 해당 기사 내의 문자열을 추출할 수도 있습니다:) 단어 추출을 위한 방법들도 여러 버전들이 있는데요, 관심 있는 주제의 리포트나 기사들 또는 각종 문학 작품 등을 재료 삼아서 연습해본 결과들도 올려보겠습니다. 

※ Pandas 참고자료 : 판다스 10분 완성(10 Minutes to Pandas)

konlpy API 바로가기

반응형