[재능상품] Python을 이용한 웹 크롤링 및 워드 클라우드 시각화

 정보

  • 업무명     : Python을 이용한 웹 크롤링 및 워드 클라우드 시각화

  • 작성자     : 이상호

  • 작성일     : 2020-12-01

  • 설   명      :

  • 수정이력 :

 

 내용

[개요]

  • 안녕하세요? 웹 개발 및 연구 개발을 담당하고 있는 해솔입니다.

  • 다년간 축적된 경험 (기상학 학술 보고서 및 국/영문 학술 논문 게재, 블로그 운영, IT 회사 웹 개발 담당) 및 노하우를 바탕으로 개개인에게 맞춤형 솔루션을 수행할 수 있습니다.

  • 특히 재능 플랫폼 (크몽, 오투잡, 해피캠퍼스, 레포트 월드)에서 누구보다도 경쟁력 있는 가격으로 양질의 서비스를 제공하고 있습니다.

    • 아스키 형식의 텍스트 (text) 파일부터 과학자료 형식 (HDF, H5, NetCDF, Grib, Grb) 및 Data Base (DB) 자료까지 다양한 형태의 자료를 이용하여 수집, 전처리, 분석, 시각화해 드립니다.

    • 또한 웹 사이트에 대한 정보를 이용한 웹 크롤링 및 그에 따른 엑셀 및 DB 구축도 가능합니다.

    • 아울러 기초 통계 (빈도분포, Prired t-test, Wilcoxn 등)에서 지도/비지도 학습을 통한 회귀모형 구축에 이르기 까지 효율적인 통계 정보를 제공합니다.

    • 최근 대한민국의 후속위성인 천리안위성 2A호 웹 서비스 서브시스템 및 환경위성 2B호 통합 자료처리 서브시스템에 대한 웹 개발을 수행하였습니다.

  • 그리고 해솔 블로그에서는 다양한 기상학/천문학 정보와 더불어 사무 자동화/프로그래밍 언어를 소개하오니 방문 부탁드립니다.

  • 좋은 하루 보내세요.

 

[재능플랫폼] 오투잡

 

[IT개발 - 응용프로그래밍] 통계 분석, 데이터 분석, 시각화를 성실하게 해 드립니다. - 재능마켓 �

판매가격:10,000원, [소개] - 데이터산업진흥원 데이터 가공 공급기업 선정 - 정보통신산업 진흥원 데이터 가공 공급기업 선정 - 다년간 축적된 경험 노하우를 바탕으로 개개인에게 맞춤형 솔루션�

www.otwojob.com

 

[재능플랫폼] 크몽

 

데이터수집, 파싱, 크롤링 해 드립니다. | 50,000원부터 시작 가능한 총 평점 0점의 IT·프로그래밍,

0개 총 작업 개수 완료한 총 평점 0점인 shlee1990의 IT·프로그래밍, 데이터분석·리포트, 데이터 마이닝·크롤링 서비스를 0개의 리뷰와 함께 확인해 보세요. IT·프로그래밍, 데이터분석·리포트, 데

kmong.com

 

 요청

[세부 사항]

  • 기사 내용을 스크랩하십시오.

  • 기사 내용을 사전 처리하여 불용어없이 단수 명사 목록을 얻습니다.

  • 빈도분포 및 워드 클라우드 시각화

 

 

A 110 million-year-old dinosaur fossil reveals its last meal

A dinosaur with impressive armored plates across its back became mummified around 110 million years ago, and now we know what this nodosaur ate for its last meal, according to a new study.

www.cnn.com

 

etc-image-0

 

 완료

[사용 OS]

  • Windows 10

 

[사용 언어]

  • Python v3.8.5

 

[명세]

  • 라이브러리 읽기 및 로그 설정

import logging as log
import sys

import matplotlib.pyplot as plt
import pandas as pd
from urllib.request import urlopen
from bs4 import BeautifulSoup
from wordcloud import WordCloud
from dfply import filter_by, group_by, summarize, ungroup, arrange, n, X
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

# 로그 설정
log.basicConfig(stream=sys.stdout, level=log.INFO,
                format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")

 

  • 웹 스크래핑

# 1) https://edition.cnn.com/2020/06/02/world/nodosaur-fossil-stomach-contents-scn-trnd/index.html에서 기사 내용을 스크랩하십시오.
html = urlopen("https://edition.cnn.com/2020/06/02/world/nodosaur-fossil-stomach-contents-scn-trnd/index.html")
# html = requests.get(url)
soup = BeautifulSoup(html, 'html.parser')

section = soup.select('section.zn-body-text')

liGetText = []
for i in section:
    getText = i.get_text()

    log.info("getText : {%s} : {%s}", len(getText), getText)

 

그림.png

 

  • 기사 내용에서 불용어없이 단수 명사 추출

liGetText = []
for i in section:
    getText = i.get_text()

    log.info("getText : {%s} : {%s}", len(getText), getText)

    # 단어 추출
    wordTokens = word_tokenize(getText)
    # 불용어
    stopWords = set(stopwords.words('english'))

    log.info("wordTokens : {%s} : {%s}", len(wordTokens), wordTokens)
    log.info("stopWords : {%s} : {%s}", len(stopWords), stopWords)

    # 2) 기사 내용을 사전 처리하여 불용어없이 단수 명사 목록을 얻습니다.
    for j in wordTokens:
        if j not in stopWords:
            liGetText.append(j)

log.info("liGetText : {%s} : {%s}", len(liGetText), liGetText)

 

그림2.png

 

 

  • 빈도 분포

data = pd.DataFrame({
    'type': liGetText
})

# 3) 빈도분포 및 워드 클라우드 시각화
dataL1 = (
    (data >>
        filter_by(
            X.type != '.'
            , X.type != ','
            , X.type != "'"
            , X.type != "''"
            , X.type != "``"
            , X.type != "'s"
        ) >>
        group_by(X.type) >>
        summarize(number=n(X.type)) >>
        ungroup() >>
        arrange(X.number, ascending=False)
        ))

log.info("dataL1 : {%s} : {%s}", len(dataL1), dataL1)

 

etc-image-3

 

  • 데이터 시각화를 위한 전처리 및 워드 클라우드

# 데이터 시각화를 위한 전처리
objData = {}
for i in dataL1.values:
    key = i[0]
    val = i[1]

    objData[key] = val

log.info("objData : {%s} : {%s}", len(objData), objData)

wordcloud = WordCloud(
    width=1000
    , height=1000
    , background_color="white"
).generate_from_frequencies(objData)

plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.savefig('E:/02. 블로그/PyCharm/resources/image/Image01.png', width=1000, heiht=1000, dpi=600)
# plt.show()

 

etc-image-4

 

Image01.png

 

[소스 코드]

#===============================================================================================
# Routine : Main program
#
# Purpose : 재능상품 오투잡
#
# Author : 해솔
#
# Revisions: V1.0 May 28, 2020 First release (MS. 해솔)
#===============================================================================================

import logging as log
import sys

import matplotlib.pyplot as plt
import pandas as pd
from urllib.request import urlopen
from bs4 import BeautifulSoup
from wordcloud import WordCloud
from dfply import filter_by, group_by, summarize, ungroup, arrange, n, X
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

# 로그 설정
log.basicConfig(stream=sys.stdout, level=log.INFO,
                format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")

# 제출할 내용 :
# -파이썬 코드 파일
# -단어 구름 시각화를위한 이미지 파일

# python -c "import nltk; nltk.download('punkt')"
# nltk.download('stopwords')

# 1) https://edition.cnn.com/2020/06/02/world/nodosaur-fossil-stomach-contents-scn-trnd/index.html에서 기사 내용을 스크랩하십시오.
html = urlopen("https://edition.cnn.com/2020/06/02/world/nodosaur-fossil-stomach-contents-scn-trnd/index.html")
# html = requests.get(url)
soup = BeautifulSoup(html, 'html.parser')

section = soup.select('section.zn-body-text')

liGetText = []
for i in section:
    getText = i.get_text()

    log.info("getText : {%s} : {%s}", len(getText), getText)

    # 단어 추출
    wordTokens = word_tokenize(getText)
    # 불용어
    stopWords = set(stopwords.words('english'))

    log.info("wordTokens : {%s} : {%s}", len(wordTokens), wordTokens)
    log.info("stopWords : {%s} : {%s}", len(stopWords), stopWords)

    # 2) 기사 내용을 사전 처리하여 불용어없이 단수 명사 목록을 얻습니다.
    for j in wordTokens:
        if j not in stopWords:
            liGetText.append(j)

log.info("liGetText : {%s} : {%s}", len(liGetText), liGetText)

data = pd.DataFrame({
    'type': liGetText
})

# 3) 빈도분포 및 워드 클라우드 시각화
dataL1 = (
    (data >>
        filter_by(
            X.type != '.'
            , X.type != ','
            , X.type != "'"
            , X.type != "''"
            , X.type != "``"
            , X.type != "'s"
        ) >>
        group_by(X.type) >>
        summarize(number=n(X.type)) >>
        ungroup() >>
        arrange(X.number, ascending=False)
        ))

log.info("dataL1 : {%s} : {%s}", len(dataL1), dataL1)

# 데이터 시각화를 위한 전처리
objData = {}
for i in dataL1.values:
    key = i[0]
    val = i[1]

    objData[key] = val

log.info("objData : {%s} : {%s}", len(objData), objData)

wordcloud = WordCloud(
    width=1000
    , height=1000
    , background_color="white"
).generate_from_frequencies(objData)

plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.savefig('E:/02. 블로그/PyCharm/resources/image/Image01.png', width=1000, heiht=1000, dpi=600)
# plt.show()

 

[결과물]

  • 워드 클라우드

Image01.png

 

 참고 문헌

[논문]

  • 없음

[보고서]

  • 없음

[URL]

  • 없음

 

 문의사항

[기상학/프로그래밍 언어]

  • sangho.lee.1990@gmail.com

[해양학/천문학/빅데이터]

  • saimang0804@gmail.com