brunch

You can make anything
by writing

C.S.Lewis

by Viel Liebe Sep 18. 2020

#15-1 워드클라우드 코드

*Python 언어를 사용한 웹 크롤링 + 형태소 분석 + 워드클라우딩 툴을 만듭니다. Python 언어를 안다는 전제 하에 간단한 설명만 덧붙였습니다.

**#8-1, #11-1 때와 비슷하지만 구글검색의 이미지결과 페이지 안의 정보체계가 달라져서 크롤링 코드를 상당 부분 수정했습니다.

***워드클라우드 코드를 구성할 때 아래 링크한 페이지를 많이 참고했습니다.

https://myjamong.tistory.com/48


from bs4 import BeautifulSoup #파싱

from tqdm import tqdm #진행상황 표시

import time #자동 딜레이

from selenium import webdriver #셀레늄

from selenium.webdriver.common.keys import Keys #페이지 내리기

import konlpy #헝태소분석기

from collections import Counter

from konlpy.tag import Twitter #트위터 형태소분석 활용

from wordcloud import WordCloud #워드클라우드

import matplotlib.pyplot as plt


#크롤링 범위

title_nums=range(0,100)


#리스트

Title_list=[]


#페이지 열기

Street_url='https://www.google.com/search?q=%EA%B8%B8%EA%B1%B0%EB%A6%AC&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiAirGNoN7rAhVTA4gKHY4jB1MQ_AUoAXoECAsQAw&cshid=1599729569503265&biw=1920&bih=969#imgrc=Y1uvjgFx5BMotM'

driver=webdriver.Chrome()

driver.get(Street_url)


#스크롤 내리기

body = driver.find_element_by_css_selector('body')

for i in range(20):

    body.send_keys(Keys.PAGE_DOWN)

    time.sleep(1)


#파싱과 크롤링

k=1

for title in tqdm(range(100)):

    if k%25==0:

        pass

    else:

        xpath='//*[@id="islrg"]/div[1]/div['+str(k)+']'

        driver.find_element_by_xpath(xpath).click()

        source=driver.page_source

        bs=BeautifulSoup(source, 'html.parser')

        each_title=bs.select_one('div.ZUo4Ze > a').text

        Title_list.append(each_title)

        driver.find_element_by_xpath('//*[@id="Sva75c"]/div/div/div[2]/a').click()

    time.sleep(0.7)

    k=k+1

#구글검색의 이미지 결과 창에서 이제는 제목을 따올 수 없습니다. 각 이미지를 클릭하면 뜨는 부분적 팝업창?에서 제목을 따와야 해서, 클릭하고 취소하는 과정을 반복하게 만들었습니다.

#워드 클라우드

def make_wordcloud(word_count):

    twitter = Twitter()    #보통 사용자사전을 추가하고 싶으면 Komoran 를 이용하긴 하지만, Twitter도 필요한 경우 ckonlpy(customized konlpy)를 설치하면 Twitter 사용자사전도 추가할 수 있습니다.

    sentences_tag = []

    #형태소 분석하여 리스트에 넣기

    for sentence in Title_list:

        morph = twitter.pos(sentence)

        sentences_tag.append(morph)

        print(morph)

        print('-' * 30) 

    print(sentences_tag)

    print('\n' * 3) 

    noun_adj_list = []

#어떤 경우에 이 과정에서 UnicodeEncodeError가 발생할 수 있는데, 해당 오류가 발생하는 구절을 try/except 문으로 바꾸어 except: pass 해주면 해결됩니다. 

    #명사와 형용사만 구분하여 이스트에 넣기

    for sentence1 in sentences_tag:

        for word, tag in sentence1:

            if len(word)>1 and tag in ['Noun', 'Adjective']:    #단어 길이가 1인 경우를 제외하지 않으면 워드클라우드 결과가 지저분해지는 경우가 생기곤 합니다.

                noun_adj_list.append(word)


    #형태소별 count

    counts = Counter(noun_adj_list)

    tags = counts.most_common(word_count)

    print(tags) 

    #wordCloud생성

    #한글꺠지는 문제 해결하기위해 font_path 지정

    wc = WordCloud(font_path='C:/Windows/Fonts/malgun.ttf', background_color='white', width=800, height=600)

    print(dict(tags))

    cloud = wc.generate_from_frequencies(dict(tags))

    plt.figure(figsize=(10, 8))

    plt.axis('off')

    plt.imshow(cloud)

    plt.show()


make_wordcloud(30)


매거진의 이전글 #15 워드클라우드 결과
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari