웹 크롤러+워드클라우드

python으로 보기싫은 좃선, 중앙 제안 키워드를 빼고 뉴스를 검색해 보자. 계획은 아래와 같다.

  • 웹 크롤러를 만들어 조선, 중앙 인터넷 페이지를 접속한다.
  • 헤드라인을 긁어 파일로 저장한다.
  • 파일을 읽어 워드클라우드로 주요 키워드를 확인한다.
  • 구글뉴스로 키워드를 검색어 제외한다.

웹 크롤러는 인터넷에 많이 공개되어 있어 쉽게 만들었다. 코드 몇 줄로 원하는 기능을 구현했다. 어려웠던 점은 복사한 코드를 수정한 점이다. 인터넷 코드가 json 형식으로 파일을 저장했다. 이를 텍스트로 변경하는 과정에 문제가 있었다. csv의 writerow를 dictionary 인자로 넣으면 한 글자마다 컴마를 찍는다. dictionary를 [] 괄호로 감싸야 된다.

워드클라우드 역시 쉽다. 한글폰트를 명시하여 generate하면 바로 된다. 나머지 부족한 부분(plot을 파일로 저장 등)을 과거 코드에서 복사해서 해결했다.

구글뉴스가 – 기호로 검색어를 제외하는 기능을 제공한다. +키워드없이 모두 -로 넣으면 범위를 너무 크게 잡는다. 한국어, 최근 1주일 등 범위를 좁혔다. 검색어 제외와 보통 검색을 비교해 보면 좀 효과가 있는 듯 하다.

# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import os
import csv

from wordcloud import WordCloud

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt


BASE_DIR = os.path.dirname(os.path.abspath(__file__))

req = requests.get('http://www.chosun.com/')
req.encoding=None
html = req.text


soup = BeautifulSoup(html, 'html.parser')


#조선일보는 dl형식으로 헤드라인을 작성한다.
my_contents = soup.find_all('dl', {'class':'news_item'}, 'dt')


data = {}


#임의의 키를 만들어서 저장.
index = 0

for content in my_contents:
    data[index] = content.text
    index = index + 1


###중앙일보
req = requests.get('https://joongang.joins.com/')
req.encoding=None
html = req.text
soup = BeautifulSoup(html, 'html.parser')

#중알일보는 li형식으로 헤드라인을 만든다.
my_contents = soup.find_all('li')


for content in my_contents:
    data[index] = content.text
    index = index + 1

print(data.values())

with open(os.path.join(BASE_DIR, 'result.csv'), 'w', encoding='utf8') as csv_file:
    writer = csv.writer(csv_file)
    for key in data.keys():
    #writer = csv.DictWriter(csv_file, data.keys())
    #writer = csv.writer(csv_file, delimiter=',')
        #print(data[key])
        writer.writerow([data[key]])

csv_file.close()

##word cloud


text = open(os.path.join(BASE_DIR, 'result.csv'), 'r', encoding='utf8').read()

#한글 폰트를 사용하기 위해, 명시
wordcloud = WordCloud(font_path='/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf', background_color='white').generate(text)

plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
plt.savefig('./wordcloud.jpg',format='jpg', dpi=300)

고해상도 이미지를 원하면 아래와 같이 작업한다.

wordcloud = WordCloud(width=800, height=400).generate(text)
plt.figure( figsize=(20,10) )
plt.imshow(wordcloud)

참조 사이트

https://datamod.tistory.com/104

json으로 저장할 경우, utf8 방식으로 저장.

https://beomi.github.io/2017/01/20/HowToMakeWebCrawler/

웹 크롤러 기본.

http://pythonstudy.xyz/python/article/403-%ED%8C%8C%EC%9D%B4%EC%8D%AC-Web-Scraping

requests 한글 사용.

https://twpower.github.io/84-how-to-use-beautiful-soup

beautifulsoup 기본.

https://medium.com/@gis10kwo/converting-nested-json-data-to-csv-using-python-pandas-dc6eddc69175

json to csv, pandas

https://www.programiz.com/python-programming/working-csv-files

write to csv

https://stackoverflow.com/questions/1816880/why-does-csvwriter-writerow-put-a-comma-after-each-character

writerow 할 때, 각 글자뒤에 comma 삽입될 때.

https://myjamong.tistory.com/48

wordcloud 사용에 한글 폰트 설정

https://stackoverflow.com/questions/28786534/increase-resolution-with-word-cloud-and-remove-empty-border/28795577

고해상도 wordcloud

코멘트

댓글 남기기

이 사이트는 Akismet을 사용하여 스팸을 줄입니다. 댓글 데이터가 어떻게 처리되는지 알아보세요.